currently working on a tic tac toe game in java, and I have a checkWin() method that works correctly for 3 out of the 4 possible winning conditions. The one I am having an issue with is the right diagonal.
Code:
public boolean checkWin(String player){
int row = 0; // Holder to count number of player spots in row
int d1 = 0; // Holder to count number of player spots in right diag.
int d2 = 0; // Holder to count number of player spots in left diag.
int[] column = new int[squares[0].length]; /* Holder to count number
of player spots in column */
for(int i = 0; i < size; i++){
row = 0;
for(int j = 0; j < size; j++){
if(null == squares[i][j]){
continue;
}
if(squares[i][j].getText().equals(player)){
row++; /* If spot at [i][j] equals player, increase row */
column[j]++; /* If spot at [i][j] equals player, increase
col */
if(i == j){ /* If spot at i is equal to j, increase left
diag */
d1++;
} else if ((size - 1) == i + j){ /* If spot at i + j
equals board size - 1, increase right diag. */
d2++;
}
}
}
if(row == size){
/*
if spots in row is equal to size (otherwise, if it fills
the row, return win
*/
return true;
}
}
if(size == d1 || size == d2){
/*
if spots in either diag is equal to size, return win
*/
return true;
}
for(int i = 0; i < column.length; i++){
if(column[i] == size){
/*
if column is full of the same player character, return win
*/
return true;
}
}
/*
otherwise, return false
*/
return false;
}
The problem part is:
else if ((size - 1) == i + j){ /* If spot at i + j
equals board size - 1, increase right diag. */
d2++;
}
Reason for setting it up this way, is how a 2D Array works, so for a 3x3 board:
[00][01][02]
[10][11][12]
[20][21][22]
And with i + j = size - 1, it would evaluate 2 + 0, 1 + 1, 0 + 2 all equal 2, which is size - 1 if size = 3, but when I run the program and perform the right diagonal move, it doesn't return a true value for win.
Any suggestions for how to fix this will be greatly appreciated.
else if ((size - 1) == i + j)
^ This is only evaluated if the if
condition above it is false.
if(i == j)
When i == 1
and j == 1
, then i == j
is true, and thus (size - 1) == i + j
is not evaluated.
TLDR: Get rid of your else
.