编写一个java小程序,实现五子棋游戏功能。
时间: 2024-02-18 18:03:22 浏览: 101
java编的五子棋小程序
好的,我可以为您解答,以下是一个简单的五子棋游戏的Java程序:
```java
import java.util.Scanner;
public class GomokuGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[][] board = new char[15][15]; // 棋盘大小为15*15
initBoard(board); // 初始化棋盘
printBoard(board); // 打印棋盘
int x, y;
char player = 'X'; // X先手,O后手
while (true) {
System.out.print("请输入" + player + "的落子位置(x,y): ");
x = scanner.nextInt();
y = scanner.nextInt();
if (isValid(board, x, y)) {
board[x][y] = player; // 落子
printBoard(board); // 打印棋盘
if (isWin(board, x, y)) {
System.out.println(player + "获胜!");
break;
}
player = (player == 'X') ? 'O' : 'X'; // 交换玩家
} else {
System.out.println("无效位置,请重新输入!");
}
}
}
// 初始化棋盘
public static void initBoard(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = '+';
}
}
}
// 打印棋盘
public static void printBoard(char[][] board) {
System.out.print(" ");
for (int i = 0; i < board.length; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
// 判断位置是否有效
public static boolean isValid(char[][] board, int x, int y) {
if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) {
return false;
}
return board[x][y] == '+';
}
// 判断是否获胜
public static boolean isWin(char[][] board, int x, int y) {
int count = 0;
char player = board[x][y];
// 水平方向
for (int i = y - 4; i <= y + 4; i++) {
if (i < 0 || i >= board.length) {
continue;
}
if (board[x][i] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 垂直方向
for (int i = x - 4; i <= x + 4; i++) {
if (i < 0 || i >= board[0].length) {
continue;
}
if (board[i][y] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 左上到右下方向
for (int i = x - 4, j = y - 4; i <= x + 4 && j <= y + 4; i++, j++) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
continue;
}
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
count = 0;
// 右上到左下方向
for (int i = x - 4, j = y + 4; i <= x + 4 && j >= y - 4; i++, j--) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
continue;
}
if (board[i][j] == player) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
}
```
这个程序使用二维数组来表示棋盘,每个位置用字符表示落子情况(‘+’表示空位,‘X’表示X方落子,‘O’表示O方落子)。程序实现了以下功能:
1. 初始化棋盘
2. 打印棋盘
3. 输入玩家落子位置,落子,并判断是否有效和是否获胜
4. 交换玩家
希望能够帮到您!
阅读全文