生成 五子棋代码 java
时间: 2023-05-23 12:05:19 浏览: 61
A:
以下是一个简单的五子棋代码示例,使用Java语言编写:
import java.util.Scanner;
public class FiveChess {
public static final int BOARD_SIZE = 15; // 棋盘大小
public static final int EMPTY = 0; // 空棋子
public static final int BLACK = 1; // 黑棋子
public static final int WHITE = 2; // 白棋子
public static void main(String[] args) {
int[][] board = new int[BOARD_SIZE][BOARD_SIZE]; // 初始化棋盘
Scanner scanner = new Scanner(System.in);
int player = BLACK; // 黑方先手
int row, col;
while (true) {
System.out.print("Player " + player + " input row and col: ");
row = scanner.nextInt();
col = scanner.nextInt();
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) { // 越界检查
System.out.println("Invalid input. Please try again.");
continue;
}
if (board[row][col] != EMPTY) { // 该位置已有棋子
System.out.println("This position has been taken. Please try again.");
continue;
}
board[row][col] = player; // 下子
if (win(board, row, col)) { // 判断胜利
System.out.println("Player " + player + " wins!");
break;
}
player = (player == BLACK ? WHITE : BLACK); // 轮换玩家
}
}
// 判断是否胜利
public static boolean win(int[][] board, int row, int col) {
int count = 1; // 记录连续棋子数量
int color = board[row][col];
int i, j;
// 水平方向检查
for (i = col - 1; i >= 0 && board[row][i] == color; i--) {
count++;
}
for (i = col + 1; i < BOARD_SIZE && board[row][i] == color; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 垂直方向检查
count = 1;
for (i = row - 1; i >= 0 && board[i][col] == color; i--) {
count++;
}
for (i = row + 1; i < BOARD_SIZE && board[i][col] == color; i++) {
count++;
}
if (count >= 5) {
return true;
}
// 左上到右下方向检查
count = 1;
for (i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] == color; i--, j--) {
count++;
}
for (i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == color; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// 右上到左下方向检查
count = 1;
for (i = row - 1, j = col + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == color; i--, j++) {
count++;
}
for (i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == color; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
}
以上代码实现了基本的五子棋游戏逻辑,包括:
- 棋盘的初始化和打印;
- 玩家的输入和下子;
- 胜利状态的判断。
需要注意的是,该示例代码仅实现了最基本的检查,还存在一些需要改进的地方,例如:
- 没有实现禁手规则;
- 没有考虑平局的情况;
- 没有实现人机对战或者网络对战等高级功能。