java双人对战五子棋
时间: 2023-08-10 16:05:55 浏览: 106
下面是一个简单的双人对战五子棋的 Java 代码示例:
```java
import java.util.Scanner;
public class Gobang {
// 定义棋盘大小
public static final int BOARD_SIZE = 15;
// 定义棋盘数组
private String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
// 定义当前玩家和对手的棋子颜色
private String currentPlayer;
private String opponent;
public Gobang() {
// 初始化棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
// 随机选择先手
if (Math.random() > 0.5) {
currentPlayer = "X";
opponent = "O";
} else {
currentPlayer = "O";
opponent = "X";
}
}
// 输出棋盘
public void printBoard() {
System.out.println(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((i + 1) + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
// 判断游戏是否结束
public boolean isGameOver(int x, int y) {
// 判断横向是否有五个棋子相连
int count = 1;
for (int i = y + 1; i < BOARD_SIZE && board[x][i].equals(currentPlayer); i++) {
count++;
}
for (int i = y - 1; i >= 0 && board[x][i].equals(currentPlayer); i--) {
count++;
}
if (count >= 5) {
return true;
}
// 判断纵向是否有五个棋子相连
count = 1;
for (int i = x + 1; i < BOARD_SIZE && board[i][y].equals(currentPlayer); i++) {
count++;
}
for (int i = x - 1; i >= 0 && board[i][y].equals(currentPlayer); i--) {
count++;
}
if (count >= 5) {
return true;
}
// 判断右斜向是否有五个棋子相连
count = 1;
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j].equals(currentPlayer); i++, j++) {
count++;
}
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j].equals(currentPlayer); i--, j--) {
count++;
}
if (count >= 5) {
return true;
}
// 判断左斜向是否有五个棋子相连
count = 1;
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j].equals(currentPlayer); i++, j--) {
count++;
}
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j].equals(currentPlayer); i--, j++) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
// 开始游戏
public void start() {
Scanner scanner = new Scanner(System.in);
int x, y;
while (true) {
// 输出当前棋盘和玩家提示
printBoard();
System.out.println("轮到 " + currentPlayer + " 玩家落子,请输入坐标(如:3,4):");
// 获取玩家输入的坐标
String input = scanner.next();
String[] inputArray = input.split(",");
x = Integer.parseInt(inputArray[0]) - 1;
y = Integer.parseInt(inputArray[1]) - 1;
// 判断坐标是否合法
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || !board[x][y].equals("+")) {
System.out.println("坐标不合法,请重新输入!");
continue;
}
// 在棋盘上落子
board[x][y] = currentPlayer;
// 判断游戏是否结束
if (isGameOver(x, y)) {
System.out.println(currentPlayer + " 玩家获胜!");
break;
}
// 切换玩家
String temp = currentPlayer;
currentPlayer = opponent;
opponent = temp;
}
scanner.close();
}
public static void main(String[] args) {
Gobang game = new Gobang();
game.start();
}
}
```
这段代码实现了一个简单的双人对战五子棋游戏,玩家可以通过输入坐标来落子,程序会自动判断是否有玩家获胜。注意,这段代码还没有实现悔棋、保存游戏等功能,你可以根据需要进行扩展。
阅读全文