Tic-Tac-Toe(井字棋)是一种简单的两人对弈游戏,通常在3x3的网格上进行。玩家轮流在网格的空格中填入“X”或“O”,先在横向、纵向或对角线上连成一线的玩家获胜。
假设我们有一个简单的Tic-Tac-Toe游戏,玩家在控制台中输入坐标来下棋。我们需要检查绘图结果,判断是否有玩家获胜。
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char currentPlayer;
public TicTacToe() {
board = new char[3][3];
currentPlayer = 'X';
initializeBoard();
}
private void initializeBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = '-';
}
}
}
public void printBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public boolean makeMove(int row, int col) {
if (row < 0 || row >= 3 || col < 0 || col >= 3 || board[row][col] != '-') {
return false;
}
board[row][col] = currentPlayer;
return true;
}
public boolean checkWin() {
// Check rows, columns and diagonals
for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
return true;
}
if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) {
return true;
}
}
if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) {
return true;
}
if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) {
return true;
}
return false;
}
public void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
Scanner scanner = new Scanner(System.in);
boolean gameOver = false;
while (!gameOver) {
game.printBoard();
System.out.println("Player " + game.currentPlayer + ", enter your move (row col): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (game.makeMove(row, col)) {
if (game.checkWin()) {
game.printBoard();
System.out.println("Player " + game.currentPlayer + " wins!");
gameOver = true;
} else {
game.switchPlayer();
}
} else {
System.out.println("Invalid move, try again.");
}
}
scanner.close();
}
}
printBoard
方法正确显示当前棋盘状态。通过上述代码和解释,你应该能够实现一个基本的Tic-Tac-Toe游戏,并检查绘图结果。如果有更多具体问题或需要进一步的优化,请提供详细信息。
领取专属 10元无门槛券
手把手带您无忧上云