用java代码写五子棋功能的代码
时间: 2024-05-08 18:19:37 浏览: 62
我可以回答你的问题,以下是一个可能的五子棋游戏的Java代码实现:
```java
import java.util.Scanner;
public class Gobang {
private static char[][] board; // 棋盘
private static final int BOARD_SIZE = 15; // 棋盘大小
private static char player = 'X'; // 当前玩家,先手执黑
public static void main(String[] args) {
initBoard(); // 初始化棋盘
printBoard(); // 打印棋盘
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请 " + player + " 玩家落子,输入行和列的坐标:");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (isValidMove(row, col)) { // 判断落子是否合法
board[row][col] = player; // 执行落子
printBoard(); // 打印棋盘
if (isGameOver(row, col)) { // 判断游戏是否结束
System.out.println(player + " 玩家获胜!");
break;
}
player = (player == 'X') ? 'O' : 'X'; // 切换玩家
} else {
System.out.println("落子不合法,请重新输入行和列的坐标!");
}
}
scanner.close();
}
private static void initBoard() {
board = new char[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '-';
}
}
}
private static void printBoard() {
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();
}
}
private static boolean isValidMove(int row, int col) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return false; // 落子超出棋盘范围
}
if (board[row][col] != '-') {
return false; // 已有棋子
}
return true;
}
private static boolean isGameOver(int row, int col) {
char piece = board[row][col];
int count = 0;
// 水平方向
for (int i = col - 4; i <= col + 4; i++) {
if (i >= 0 && i < BOARD_SIZE && board[row][i] == piece) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 垂直方向
for (int i = row - 4; i <= row + 4; i++) {
if (i >= 0 && i < BOARD_SIZE && board[i][col] == piece) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 正斜方向
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col + i;
if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == piece) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 反斜方向
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col - i;
if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE && board[r][c] == piece) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
}
```
如果你有其他问题,欢迎继续追问。
阅读全文