写出java实现五子棋的代码
时间: 2023-10-09 22:05:20 浏览: 57
好的,下面是一个简单的 Java 实现五子棋的代码,仅供参考:
```
import java.util.Scanner;
public class Gobang {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] chessboard = new int[15][15]; // 棋盘
int player = 1; // 玩家1为黑子,玩家2为白子
int count = 0; // 记录已落子数
boolean isWin = false; // 判断是否获胜
int x = 0, y = 0; // 记录玩家落子的位置
// 绘制棋盘
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
// 玩家落子
while (!isWin && count < 225) {
// 玩家输入落子位置
System.out.println("请玩家" + player + "输入落子位置(例如:3 4):");
x = scanner.nextInt();
y = scanner.nextInt();
// 判断位置是否合法
if (x >= 0 && x < 15 && y >= 0 && y < 15 && chessboard[x][y] == 0) {
chessboard[x][y] = player;
count++;
isWin = checkWin(chessboard, x, y, player);
player = player == 1 ? 2 : 1; // 切换玩家
} else {
System.out.println("落子位置不合法,请重新输入!");
}
}
// 输出获胜信息
if (isWin) {
System.out.println("玩家" + (player == 1 ? 2 : 1) + "获胜!");
} else {
System.out.println("平局!");
}
}
// 判断是否获胜
public static boolean checkWin(int[][] chessboard, int x, int y, int player) {
int count = 0;
// 横向判断
for (int i = Math.max(0, x - 4); i <= Math.min(14, x + 4); i++) {
if (chessboard[i][y] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 纵向判断
count = 0;
for (int j = Math.max(0, y - 4); j <= Math.min(14, y + 4); j++) {
if (chessboard[x][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 左上到右下判断
count = 0;
for (int i = Math.max(0, x - 4), j = Math.max(0, y - 4); i <= Math.min(14, x + 4) && j <= Math.min(14, y + 4); i++, j++) {
if (chessboard[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
// 右上到左下判断
count = 0;
for (int i = Math.max(0, x - 4), j = Math.min(14, y + 4); i <= Math.min(14, x + 4) && j >= Math.max(0, y - 4); i++, j--) {
if (chessboard[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
return false;
}
}
```
这个代码只是一个简单的实现,你可以根据自己的需求进行修改和优化。