能用java给我写个五子棋游戏吗
时间: 2023-07-05 09:24:22 浏览: 48
当然可以,以下是一个简单的五子棋游戏的Java实现,供您参考:
```java
import java.util.Scanner;
public class FiveChess {
private int[][] board; // 棋盘
private boolean over; // 是否结束
private int turn; // 当前轮到哪个玩家下棋
// 构造函数,初始化棋盘
public FiveChess() {
board = new int[15][15];
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = 0; // 0表示空,1表示黑,2表示白
}
}
over = false;
turn = 1; // 黑方先手
}
// 判断当前位置是否可下子
public boolean validMove(int x, int y) {
return x >= 0 && y >= 0 && x < 15 && y < 15 && board[x][y] == 0;
}
// 判断当前局面是否结束
public boolean gameOver(int x, int y, int color) {
// 判断行
int count = 0;
for (int i = 0; i < 15; i++) {
if (board[x][i] == color) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
// 判断列
count = 0;
for (int i = 0; i < 15; i++) {
if (board[i][y] == color) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
// 判断对角线
count = 0;
for (int i = -4; i <= 4; i++) {
if (x+i >= 0 && y+i >= 0 && x+i < 15 && y+i < 15) {
if (board[x+i][y+i] == color) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
}
// 判断反对角线
count = 0;
for (int i = -4; i <= 4; i++) {
if (x+i >= 0 && y-i >= 0 && x+i < 15 && y-i < 15) {
if (board[x+i][y-i] == color) {
count++;
} else {
count = 0;
}
if (count >= 5) {
return true;
}
}
}
return false;
}
// 打印当前棋盘
public void printBoard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if (board[i][j] == 0) {
System.out.print("+ ");
} else if (board[i][j] == 1) {
System.out.print("X ");
} else {
System.out.print("O ");
}
}
System.out.println();
}
}
// 开始游戏
public void play() {
Scanner input = new Scanner(System.in);
while (!over) {
printBoard();
if (turn == 1) {
System.out.println("黑方下棋:");
} else {
System.out.println("白方下棋:");
}
int x = input.nextInt();
int y = input.nextInt();
if (validMove(x, y)) {
board[x][y] = turn;
if (gameOver(x, y, turn)) {
printBoard();
if (turn == 1) {
System.out.println("黑方胜利!");
} else {
System.out.println("白方胜利!");
}
over = true;
}
turn = 3 - turn; // 切换到对方下棋
} else {
System.out.println("非法操作,请重新输入!");
}
}
}
public static void main(String[] args) {
FiveChess game = new FiveChess();
game.play();
}
}
```
这个程序可以在命令行中运行,每次轮流输入横坐标和纵坐标,即可下棋。当有一方连成五子时,游戏结束,并宣布胜利者。希望能够帮助到您。