当前正在用Java玩井字游戏,我有一个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,但是当我运行程序并执行右对角移动,它不会返回真正的胜利值。
任何解决此问题的建议将不胜感激。
答案 0 :(得分:1)
else if ((size - 1) == i + j)
^仅当其上方的if
条件为false时,才进行评估。
if(i == j)
当i == 1
和j == 1
时,i == j
为真,因此(size - 1) == i + j
不被评估。
TLDR:摆脱您的else
。