用java编写一个五子棋小游戏
时间: 2023-08-20 22:05:57 浏览: 99
好的,以下是一个简单的五子棋小游戏的Java代码:
```java
import java.util.Scanner;
public class GobangGame {
// 棋盘大小
private static final int BOARD_SIZE = 15;
// 玩家1用黑子,玩家2用白子
private static final String BLACK = "●";
private static final String WHITE = "○";
private String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
private boolean isBlack = true;
public static void main(String[] args) {
GobangGame game = new GobangGame();
game.initBoard();
game.startGame();
}
// 初始化棋盘
private void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
}
// 开始游戏
private void startGame() {
Scanner scanner = new Scanner(System.in);
while (true) {
// 打印棋盘
printBoard();
// 获取玩家输入的坐标
System.out.print("请输入落子的坐标(格式:x,y):");
String input = scanner.nextLine();
String[] pos = input.split(",");
int x = Integer.parseInt(pos[0]) - 1;
int y = Integer.parseInt(pos[1]) - 1;
// 判断坐标是否合法
if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE && board[x][y].equals("+")) {
// 落子
board[x][y] = isBlack ? BLACK : WHITE;
// 判断游戏是否结束
if (isWin(x, y)) {
System.out.println((isBlack ? "黑子" : "白子") + "胜利!");
break;
}
// 切换玩家
isBlack = !isBlack;
} else {
System.out.println("坐标不合法,请重新输入!");
}
}
scanner.close();
}
// 判断游戏是否结束
private boolean isWin(int x, int y) {
String piece = isBlack ? BLACK : WHITE;
int count = 1;
// 水平方向
for (int i = y - 1; i >= 0; i--) {
if (board[x][i].equals(piece)) {
count++;
} else {
break;
}
}
for (int i = y + 1; i < BOARD_SIZE; i++) {
if (board[x][i].equals(piece)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 垂直方向
count = 1;
for (int i = x - 1; i >= 0; i--) {
if (board[i][y].equals(piece)) {
count++;
} else {
break;
}
}
for (int i = x + 1; i < BOARD_SIZE; i++) {
if (board[i][y].equals(piece)) {
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].equals(piece)) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
if (board[i][j].equals(piece)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 右上到左下方向
count = 1;
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE; i--, j++) {
if (board[i][j].equals(piece)) {
count++;
} else {
break;
}
}
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0; i++, j--) {
if (board[i][j].equals(piece)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
// 打印棋盘
private void printBoard() {
System.out.print(" ");
for (int i = 1; i <= BOARD_SIZE; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((i + 1) + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
```
运行程序后,输入坐标即可进行游戏。其中,黑子用“●”表示,白子用“○”表示。
阅读全文