数组Java | TicTacToe右对角线不工作
目前正在用java开发一个tic-tac-toe游戏,我有一个checkWin()方法,可以在4种可能的获胜条件中正确地处理3种。我遇到问题的是右对角线
代码:
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;
}
问题在于:
else if ((size - 1) == i + j){ /* If spot at i + j
equals board size - 1, increase right diag. */
d2++;
}
这样设置的原因是2D阵列的工作原理,因此对于3x3板:
[00][01][02]
[10][11][12]
[20][21][22]
当i+j=size-1时,它将计算2+0,1+1,0+2都等于2,如果size=3,则为size-1,但当我运行程序并执行右对角移动时,它不会返回win的真实值
如有任何关于如何解决此问题的建议,我们将不胜感激
# 1 楼答案
^仅当其上方的
if
条件为false时,才会计算此值当
i == 1
和j == 1
时,则i == j
为真,因此(size - 1) == i + j
不计算TLDR:摆脱你的
else