我正在制作一个四子棋游戏。游戏目标是将四个物品以相同的方式排列。
我有一个双精度数组:Player[6][7]
由在该插槽上玩的玩家填充。
我正在研究胜利条件,其中包括:
- 线(工作)
- 列(工作)
- 左上角到右下角的对角线 ->不起作用
- 对角线从左下角到右上角 ->不起作用
并且对角线不起作用。
以下是我检查胜利的代码:
private final Player[][] board = new Player[6][7]; // the board filled
public Player hasWinner() {
// Lines (rows)
for(int y = 0; y < board.length; y++) { // simple lines
Player last = null;
int nb = 0;
Player[] line = board[y];
for(int x = 0; x < line.length; x++) {
Player played = line[x];
if((last == null || played == last) && played != null) { // new player or same as before
nb++;
if(nb == 4) // it's this !
return played;
} else { // else reset
nb = (played == null ? 0 : 1);
}
last = played;
}
}
// Columns
for(int x = 0; x < board[0].length; x++) { // simple columns
Player last = null;
int nb = 0;
for(int y = 0; y < board.length; y++) { // for each columns
Player played = board[y][x];
if((last == null || played == last) && played != null) { // new player or same as before
nb++;
if(nb == 4) // it's this !
return played;
} else { // else reset
nb = (played == null ? 0 : 1);
}
last = played;
}
}
// ➡️ HERE IS THE INTERESTING PART
// Diagonals
for(int i = -board.length; i < board[0].length; i++) { // diagonals
Player last = null;
int nb = 0;
for(int j = 0; j < 9; j++) {
if(board.length <= j || board[j].length <= j)
continue;
Player played = board[j][j];
if((last == null || played == last) && played != null) { // new player or same as before
nb++;
if(nb == 4) // it's this !
return played;
} else { // else reset
nb = (played == null ? 0 : 1);
}
last = played;
}
for(int j = 9; j < 0; j--) {
if(board.length <= j || board[j].length <= j)
continue;
Player played = board[j][board[j].length - j];
if((last == null || played == last) && played != null) { // new player or same as before
nb++;
if(nb == 4) // it's this !
return played;
} else { // else reset
nb = (played == null ? 0 : 1);
}
last = played;
}
}
return null;
}
我怎样才能使对角线胜利发挥作用?
避免使用像这样的魔法数字
9
。使用矩阵行和列的长度作为上限。为匹配的大小指定一个常数,即 4。对于对角线,将当前玩家与方向进行比较
[row + dy, col + dx]
。重构逻辑
有很多重复,我们可以使用方向来扫描行、列等......