用java写一个五子棋游戏的代码
时间: 2024-04-29 18:22:08 浏览: 12
好的,下面是一个简单的五子棋游戏的Java代码示例。这个示例使用控制台作为游戏界面,没有使用图形化界面,仅供参考。
```java
import java.util.Scanner;
public class FiveInARow {
private char[][] board; // 棋盘
private char player; // 当前玩家
private int size; // 棋盘大小
private int count; // 下棋步数
public FiveInARow(int size) {
this.size = size;
board = new char[size][size];
player = 'X';
count = 0;
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (true) {
// 打印棋盘
printBoard();
// 获取下棋位置
int row, col;
do {
System.out.print("Player " + player + ", enter row and column separated by space: ");
row = scanner.nextInt();
col = scanner.nextInt();
} while (!isValidMove(row, col));
// 下棋
board[row][col] = player;
count++;
// 判断胜负
if (hasWon(row, col)) {
printBoard();
System.out.println("Player " + player + " has won!");
break;
}
// 判断平局
if (count == size * size) {
printBoard();
System.out.println("It's a draw!");
break;
}
// 切换玩家
player = (player == 'X') ? 'O' : 'X';
}
scanner.close();
}
// 打印棋盘
private 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();
}
}
// 判断是否合法落子
private boolean isValidMove(int row, int col) {
if (row < 0 || row >= size || col < 0 || col >= size) {
return false;
}
if (board[row][col] != 0) {
return false;
}
return true;
}
// 判断是否胜利
private boolean hasWon(int row, int col) {
// 判断行
int count = 1;
for (int i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (int i = col + 1; i < size && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 判断列
count = 1;
for (int i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (int i = row + 1; i < size && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 判断对角线
count = 1;
for (int i = row - 1, j = col - 1; i
阅读全文