帮我写一段五子棋的java代码
时间: 2023-07-10 13:06:02 浏览: 88
五子棋的java代码
好的,下面是一份简单的五子棋Java代码,希望能对你有所帮助:
```java
import java.util.Scanner;
public class FiveInRow {
public static void main(String[] args) {
char[][] board = new char[15][15];
int row, col;
char player = 'X';
Scanner input = new Scanner(System.in);
// 初始化棋盘
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = '-';
}
}
// 开始游戏
while (true) {
// 打印棋盘
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
// 获取玩家输入
System.out.println("请" + player + "输入落子位置(行 列):");
row = input.nextInt();
col = input.nextInt();
// 判断输入是否合法
if (row < 0 || row >= 15 || col < 0 || col >= 15) {
System.out.println("输入位置不合法,请重新输入!");
continue;
}
if (board[row][col] != '-') {
System.out.println("该位置已经有棋子,请重新输入!");
continue;
}
// 落子
board[row][col] = player;
// 判断游戏是否结束
if (isGameOver(board, row, col)) {
System.out.println(player + "获胜!");
break;
}
// 换另一个玩家
player = (player == 'X' ? 'O' : 'X');
}
}
// 判断游戏是否结束
public static boolean isGameOver(char[][] board, int row, int col) {
char player = board[row][col];
int count = 0;
// 水平方向
for (int i = col - 4; i <= col + 4; i++) {
if (i < 0 || i >= 15) {
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 >= 15) {
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 >= 15 || j < 0 || j >= 15) {
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 >= 15 || j < 0 || j >= 15) {
continue;
}
if (board[i][j] == player) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
return false;
}
}
```
这份代码实现了一个简单的五子棋游戏,其中包括初始化棋盘、打印棋盘、获取玩家输入、落子、判断游戏是否结束等功能。你可以根据自己的需求修改代码。
阅读全文