Tic Tac Toe(井字棋)是一种简单的两人对弈游戏,通常在3x3的棋盘上进行。玩家轮流在空格中填入自己的标记(通常是“X”和“O”),先将自己的标记连成一条直线(水平、垂直或对角线)的玩家获胜。
在Java实现Tic Tac Toe游戏时,水平、垂直和对角线检查未生效的问题。
以下是一个简单的Java示例代码,展示如何进行水平、垂直和对角线检查:
public class TicTacToe {
private char[][] board;
private static final int SIZE = 3;
public TicTacToe() {
board = new char[SIZE][SIZE];
initializeBoard();
}
private void initializeBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = '-';
}
}
}
public boolean checkWin(char player) {
return checkRowsForWin(player) || checkColumnsForWin(player) || checkDiagonalsForWin(player);
}
private boolean checkRowsForWin(char player) {
for (int i = 0; i < SIZE; i++) {
if (checkRowCol(board[i][0], board[i][1], board[i][2], player)) {
return true;
}
}
return false;
}
private boolean checkColumnsForWin(char player) {
for (int i = 0; i < SIZE; i++) {
if (checkRowCol(board[0][i], board[1][i], board[2][i], player)) {
return true;
}
}
return false;
}
private boolean checkDiagonalsForWin(char player) {
return checkRowCol(board[0][0], board[1][1], board[2][2], player) ||
checkRowCol(board[0][2], board[1][1], board[2][0], player);
}
private boolean checkRowCol(char c1, char c2, char c3, char player) {
return c1 == player && c2 == player && c3 == player;
}
public void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
game.printBoard();
// Example move
game.board[0][0] = 'X';
game.board[1][1] = 'X';
game.board[2][2] = 'X';
game.printBoard();
System.out.println("Player X wins: " + game.checkWin('X'));
}
}
通过上述代码,可以实现对水平、垂直和对角线的检查。确保在每次玩家移动后调用checkWin
方法来检查是否有玩家获胜。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云