TicTacToe.java
import java.util.Scanner;
public class TicTacToe {
private static final int BOARD_SIZE = 3;
private static final char EMPTY_CELL = '-';
private static final char PLAYER_1_SYMBOL = 'X';
private static final char PLAYER_2_SYMBOL = 'O';
private char[][] board;
private char currentPlayerSymbol;
public TicTacToe() {
board = new char[BOARD_SIZE][BOARD_SIZE];
currentPlayerSymbol = PLAYER_1_SYMBOL;
initializeBoard();
}
private void initializeBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = EMPTY_CELL;
}
}
}
public void play() {
Scanner scanner = new Scanner(System.in);
boolean gameOver = false;
int movesCount = 0;
while (!gameOver) {
displayBoard();
int row, col;
do {
System.out.printf("Player %c's turn. Enter row (1-%d) and column (1-%d) separated by space: ",
currentPlayerSymbol, BOARD_SIZE, BOARD_SIZE);
row = scanner.nextInt() - 1;
col = scanner.nextInt() - 1;
} while (!isValidMove(row, col));
board[row][col] = currentPlayerSymbol;
movesCount++;
if (isWinningMove(row, col)) {
displayBoard();
System.out.printf("Player %c wins!\n", currentPlayerSymbol);
gameOver = true;
} else if (movesCount == BOARD_SIZE * BOARD_SIZE) {
displayBoard();
System.out.println("Game over. It's a draw.");
gameOver = true;
} else {
currentPlayerSymbol = (currentPlayerSymbol == PLAYER_1_SYMBOL) ? PLAYER_2_SYMBOL : PLAYER_1_SYMBOL;
}
}
}
private boolean isValidMove(int row, int col) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
System.out.printf("Invalid move. Row and column must be between 1 and %d.\n", BOARD_SIZE);
return false;
} else if (board[row][col] != EMPTY_CELL) {
System.out.println("Invalid move. Cell is already occupied.");
return false;
} else {
return true;
}
}
private boolean isWinningMove(int row, int col) {
boolean rowWin = true;
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[row][j] != currentPlayerSymbol) {
rowWin = false;
break;
}
}
if (rowWin) {
return true;
}
boolean colWin = true;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][col] != currentPlayerSymbol) {
colWin = false;
break;
}
}
if (colWin) {
return true;
}
boolean diagonalWin1 = true;
boolean diagonalWin2 = true;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][i] != currentPlayerSymbol) {
diagonalWin1 = false;
}
if (board[i][BOARD_SIZE - 1 - i] != currentPlayerSymbol) {
diagonalWin2 = false;
}
}
if (diagonalWin1 || diagonalWin2) {
return true;
}
return false;
}
private void displayBoard() {
System.out.println("Current board:");
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
game.play();
}
}
运行效果
