请用Java编写一个简易五子棋程序
时间: 2023-08-09 12:10:13 浏览: 109
java编写的一个简单的五子棋程序
好的,以下是一个简易五子棋程序的Java代码:
```java
import java.util.Scanner;
public class Gobang {
public static final int BOARD_SIZE = 15;
public static String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
public static void main(String[] args) {
initializeBoard();
printBoard();
Scanner scanner = new Scanner(System.in);
int x, y;
String winner = null;
boolean isBlack = true;
while (winner == null) {
System.out.print("请输入落子的坐标(x,y):");
x = scanner.nextInt();
y = scanner.nextInt();
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE) {
System.out.println("坐标不合法,请重新输入!");
continue;
}
if (board[x][y] != null) {
System.out.println("该位置已经有棋子,请重新输入!");
continue;
}
board[x][y] = isBlack ? "●" : "○";
printBoard();
isBlack = !isBlack;
winner = checkWinner(x, y);
}
System.out.println("胜者是:" + winner);
}
public static void initializeBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
}
public static void printBoard() {
System.out.print(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((char) ('a' + 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((i + 1));
}
System.out.print(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print((char) ('a' + i) + " ");
}
System.out.println();
}
public static String checkWinner(int x, int y) {
String target = board[x][y];
int count = 1;
for (int i = x + 1; i < BOARD_SIZE && board[i][y] == target; i++) {
count++;
}
for (int i = x - 1; i >= 0 && board[i][y] == target; i--) {
count++;
}
if (count >= 5) {
return target;
}
count = 1;
for (int j = y + 1; j < BOARD_SIZE && board[x][j] == target; j++) {
count++;
}
for (int j = y - 1; j >= 0 && board[x][j] == target; j--) {
count++;
}
if (count >= 5) {
return target;
}
count = 1;
for (int i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == target; i++, j++) {
count++;
}
for (int i = x - 1, j = y - 1; i >= 0 && j >= 0 && board[i][j] == target; i--, j--) {
count++;
}
if (count >= 5) {
return target;
}
count = 1;
for (int i = x + 1, j = y - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == target; i++, j--) {
count++;
}
for (int i = x - 1, j = y + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == target; i--, j++) {
count++;
}
if (count >= 5) {
return target;
}
return null;
}
}
```
该程序使用二维数组来表示棋盘,使用字符串 "●" 和 "○" 分别表示黑子和白子。程序先初始化棋盘,然后循环让玩家输入落子的坐标,检查坐标的合法性和该位置是否已经有棋子,然后更新棋盘、打印棋盘、切换玩家,并且在每次落子后检查是否有胜者出现。如果出现胜者,程序退出循环并且输出胜者的颜色。
阅读全文