五子棋源代码用JAVA实现
时间: 2023-12-14 09:02:53 浏览: 36
以下是一个简单的五子棋游戏的源代码,使用 Java 语言实现:
```java
import java.util.Scanner;
public class FiveChess {
private int boardSize = 15; // 棋盘大小
private int[][] board = new int[boardSize][boardSize]; // 棋盘数组
private int current_player = 1; // 当前玩家
public void put_chess(int x, int y) {
if (x < 0 || x >= boardSize || y < 0 || y >= boardSize) {
System.out.println("输入不合法,请重新输入!");
return;
}
if (board[x][y] != 0) {
System.out.println("此处已有棋子,请重新输入!");
return;
}
board[x][y] = current_player;
}
public boolean check_win(int x, int y) {
int[][] directions = {{0, 1}, {1, 0}, {1, 1}, {1, -1}};
for (int[] d : directions) {
int count = 1;
int dx = d[0], dy = d[1];
int tx = x+dx, ty = y+dy;
while (tx >= 0 && tx < boardSize && ty >= 0 && ty < boardSize && board[tx][ty] == current_player) {
count++;
tx += dx;
ty += dy;
}
dx = -d[0];
dy = -d[1];
tx = x+dx;
ty = y+dy;
while (tx >= 0 && tx < boardSize && ty >= 0 && ty < boardSize && board[tx][ty] == current_player) {
count++;
tx += dx;
ty += dy;
}
if (count >= 5) {
return true;
}
}
return false;
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("当前玩家:" + (current_player == 1 ? "黑方" : "白方"));
System.out.print("请输入棋子的横坐标:");
int x = scanner.nextInt();
System.out.print("请输入棋子的纵坐标:");
int y = scanner.nextInt();
put_chess(x, y);
if (check_win(x, y)) {
System.out.println((current_player == 1 ? "黑方" : "白方") + "获胜!");
break;
}
current_player = -current_player;
}
scanner.close();
}
public static void main(String[] args) {
FiveChess game = new FiveChess();
game.play();
}
}
```
运行该程序,即可开始五子棋游戏。