java井字棋eclipse
时间: 2024-01-11 10:03:54 浏览: 70
井字棋eclipse项目(java)
以下是使用Java语言在Eclipse环境下编写的井字棋游戏的示例代码:
```java
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char currentPlayer;
public TicTacToe() {
board = new char[3][3];
currentPlayer = 'X';
initializeBoard();
}
public 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 isBoardFull() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '-') {
return false;
}
}
}
return true;
}
public boolean isWinner() {
// 检查行
for (int i = 0; i < 3; i++) {
if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) {
return true;
}
}
// 检查列
for (int j = 0; j < 3; j++) {
if (board[0][j] == currentPlayer && board[1][j] == currentPlayer && board[2][j] == 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 makeMove(int row, int col) {
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-') {
board[row][col] = currentPlayer;
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
Scanner scanner = new Scanner(System.in);
while (!game.isBoardFull() && !game.isWinner()) {
System.out.println("当前玩家:" + game.currentPlayer);
System.out.print("请输入行号(0-2):");
int row = scanner.nextInt();
System.out.print("请输入列号(0-2):");
int col = scanner.nextInt();
game.makeMove(row, col);
game.printBoard();
}
if (game.isWinner()) {
System.out.println("游戏结束");
System.out.println(game.currentPlayer + "胜利");
} else {
System.out.println("游戏结束");
System.out.println("平局");
}
scanner.close();
}
}
```
阅读全文