用java帮我写一个五子棋
时间: 2023-04-01 13:03:33 浏览: 154
用Java写的五子棋
很高兴为您提供帮助。以下是一个简单的五子棋游戏的 Java 代码示例:
import java.util.Scanner;
public class GobangGame {
private static final int BOARD_SIZE = 15;
private String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
private String player1 = "●";
private String player2 = "○";
private String currentPlayer = player1;
public GobangGame() {
for (int i = ; i < BOARD_SIZE; i++) {
for (int j = ; j < BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
}
public void printBoard() {
for (int i = ; i < BOARD_SIZE; i++) {
for (int j = ; j < BOARD_SIZE; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
public boolean play(int x, int y) {
if (board[x][y].equals("+")) {
board[x][y] = currentPlayer;
return true;
} else {
return false;
}
}
public boolean checkWin(int x, int y) {
int count = 1;
int i, j;
// 横向检查
for (i = x - 1; i >= ; i--) {
if (board[i][y].equals(currentPlayer)) {
count++;
} else {
break;
}
}
for (i = x + 1; i < BOARD_SIZE; i++) {
if (board[i][y].equals(currentPlayer)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 纵向检查
count = 1;
for (j = y - 1; j >= ; j--) {
if (board[x][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
for (j = y + 1; j < BOARD_SIZE; j++) {
if (board[x][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 左上到右下检查
count = 1;
for (i = x - 1, j = y - 1; i >= && j >= ; i--, j--) {
if (board[i][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
for (i = x + 1, j = y + 1; i < BOARD_SIZE && j < BOARD_SIZE; i++, j++) {
if (board[i][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
// 右上到左下检查
count = 1;
for (i = x - 1, j = y + 1; i >= && j < BOARD_SIZE; i--, j++) {
if (board[i][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
for (i = x + 1, j = y - 1; i < BOARD_SIZE && j >= ; i++, j--) {
if (board[i][j].equals(currentPlayer)) {
count++;
} else {
break;
}
}
if (count >= 5) {
return true;
}
return false;
}
public void start() {
Scanner scanner = new Scanner(System.in);
int x, y;
while (true) {
System.out.println("当前玩家:" + currentPlayer);
printBoard();
System.out.print("请输入落子的坐标(x,y):");
x = scanner.nextInt();
y = scanner.nextInt();
if (play(x, y)) {
if (checkWin(x, y)) {
System.out.println("恭喜玩家 " + currentPlayer + " 获胜!");
break;
}
currentPlayer = currentPlayer.equals(player1) ? player2 : player1;
} else {
System.out.println("该位置已经有棋子,请重新输入!");
}
}
}
public static void main(String[] args) {
GobangGame game = new GobangGame();
game.start();
}
}
希望这个代码示例能够帮助您完成五子棋游戏的开发。
阅读全文