-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrid.java
More file actions
67 lines (57 loc) · 1.9 KB
/
Grid.java
File metadata and controls
67 lines (57 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Grid {
public int[][] board;
public Grid(int[][] board) {
//creates a multidimensional array representing the board
// where 0 is blank, 1 is x, and 2 is o.
this.board = board;
}
public boolean win(int [][] b,int player) {
// horizontal/vertical win checking code
// checks if there is a winning horizontal or vertical pattern and returns if the player won, or if there
// were no winning patterns
int horiz;
for (int row = 0; row < b.length; row++) {
horiz = 0; // resets to 0 for each new row
for (int col = 0; col < b[row].length; col++) {
if (b[row][0] == b[row][col] && b[row][0] != 0) {
horiz++;
}
if (horiz == 3) {
if (b[row][0] == player) {
return true;
}
// if the first number(which represents either an x or o, matches
// with the rest of the numbers in the row (aka if the entire row has
// the same number), return true
}
if (row == 0) {// goes through this only with the first row
if (b[0][col] == b[1][col] && b[0][col] == b[2][col] && b[0][col] != 0) {
if (b[0][col] == player) {
return true;
}
// if a number in the first row is the same as the two below it,
// return that the player won
}
}
}
}
// diagonal win checking code
// if the middle number equals the top right and bottom left numbers or equals
// the
// top left and bottom right numbers, return true to show a winning diagonal
// pattern
int mid = b[1][1];
if (mid == b[0][0] && mid == b[2][2] && mid != 0) { // top left and bottom right
if (mid == player) {
return true;
}
} else if (mid == b[0][2] && mid == b[2][0] && mid != 0) { // top right and bottom left
if (mid == player) {
return true;
}
}
// no win code
// if there are no winning patterns found, return false
return false;
}
}