写一个Java程序,可以实现五子棋双人对战
时间: 2024-03-16 14:45:10 浏览: 85
java五子棋双人对战
以下是一个简单的 Java 五子棋双人对战程序示例,您可以参考它进行开发:
```
import java.util.Scanner;
public class Gobang {
private static final int BOARD_SIZE = 15; // 棋盘大小
private static String[][] board = new String[BOARD_SIZE][BOARD_SIZE]; // 棋盘数组
public static void main(String[] args) {
initBoard(); // 初始化棋盘
printBoard(); // 打印棋盘
Scanner scanner = new Scanner(System.in);
int row, col;
String player = "X";
while (true) {
System.out.print("请 " + player + " 下棋,输入坐标(格式如 3,5):");
String input = scanner.next();
if (input.equalsIgnoreCase("exit")) {
System.out.println("游戏结束!");
break;
}
String[] coords = input.split(",");
if (coords.length != 2) {
System.out.println("无效的坐标,请重试!");
continue;
}
try {
row = Integer.parseInt(coords[0]) - 1;
col = Integer.parseInt(coords[1]) - 1;
} catch (NumberFormatException e) {
System.out.println("无效的坐标,请重试!");
continue;
}
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
System.out.println("坐标超出棋盘范围,请重试!");
continue;
}
if (board[row][col] != null) {
System.out.println("该位置已有棋子,请重试!");
continue;
}
board[row][col] = player; // 在棋盘上下子
printBoard(); // 打印棋盘
if (checkWin(row, col, player)) { // 判断是否胜利
System.out.println("恭喜 " + player + " 获得胜利!");
break;
}
player = player.equals("X") ? "O" : "X"; // 切换玩家
}
scanner.close();
}
private static void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = null; // 初始化每个位置为空
}
}
}
private static void printBoard() {
System.out.print(" ");
for (int i = 1; i <= BOARD_SIZE; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((i + 1) + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j] == null) {
System.out.print("+ ");
} else {
System.out.print(board[i][j] + " ");
}
}
System.out.println();
}
}
private static boolean checkWin(int row, int col, String player) {
// 检查水平方向
int count = 0;
for (int i = col - 4; i <= col + 4; i++) {
if (i < 0 || i >= BOARD_SIZE) {
continue;
}
if (board[row][i] == player) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
// 检查垂直方向
count = 0;
for (int i = row - 4; i <= row + 4; i++) {
if (i < 0 || i >= BOARD_SIZE) {
continue;
}
if (board[i][col] == player) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
// 检查左上-右下方向
count = 0;
for (int i = row - 4, j = col - 4; i <= row + 4 && j <= col + 4; i++, j++) {
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) {
continue;
}
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
// 检查左下-右上方向
count = 0;
for (int i = row + 4, j = col - 4; i >= row - 4 && j <= col + 4; i--, j++) {
if (i < 0 || i >= BOARD_SIZE || j < 0 || j >= BOARD_SIZE) {
continue;
}
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
return false;
}
}
```
此程序实现了一个简单的五子棋双人对战,玩家可以通过输入坐标来下棋,程序会判断胜负并打印棋盘。但这只是一个简单的示例,还有很多方面需要优化和改进,比如增加界面、加入AI等。
阅读全文