用JAVA编写一个一个五子棋小程序,要求如下: 1.棋盘15x15 2.自动判断输赢 3.当一方获胜后,提示获胜方,并标识出获胜的棋子 4.可以悔棋
时间: 2024-03-25 21:40:36 浏览: 87
JAVA编写的简单的五子棋程序
5星 · 资源好评率100%
好的,我可以为您提供一些关键的代码实现。首先,我们需要定义一个二维数组来表示棋盘,然后根据用户的输入来判断落子的位置,同时要记录每个玩家的棋子颜色。下面是一个简单的示例代码:
```java
import java.util.Scanner;
public class Gobang {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] board = new int[15][15];
int player = 1;
int x, y;
boolean win = false;
int count = 0;
while (!win && count < 225) {
System.out.println("请输入玩家 " + player + " 的落子位置(如:3 5):");
x = scanner.nextInt();
y = scanner.nextInt();
if (board[x][y] != 0) {
System.out.println("该位置已经有棋子,请重新输入!");
continue;
}
board[x][y] = player;
count++;
// 判断是否获胜
win = checkWin(board, player, x, y);
if (win) {
System.out.println("玩家 " + player + " 获胜!");
}
player = player == 1 ? 2 : 1;
}
}
private static boolean checkWin(int[][] board, int player, int x, int y) {
// 判断行
int count = 1;
for (int i = x - 1; i >= 0; i--) {
if (board[i][y] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1; i < 15; i++) {
if (board[i][y] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断列
count = 1;
for (int i = y - 1; i >= 0; i--) {
if (board[x][i] == player) {
count++;
} else {
break;
}
}
for (int i = y + 1; i < 15; i++) {
if (board[x][i] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断左上到右下的斜线
count = 1;
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y + 1; i < 15 && j < 15; i++, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 判断右上到左下的斜线
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < 15; i--, j++) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y - 1; i < 15 && j >= 0; i++, j--) {
if (board[i][j] == player) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
}
```
以上是一个最基本的五子棋程序,您可以在此基础上进行扩展,添加悔棋等功能。
阅读全文