用java编写五子棋游戏
时间: 2023-07-01 14:24:54 浏览: 50
好的,以下是一个简单的 Java 五子棋游戏示例:
```java
import java.util.Scanner;
public class GomokuGame {
private static final int BOARD_SIZE = 15;
private static final char[][] board = new char[BOARD_SIZE][BOARD_SIZE];
private static final char BLACK = 'X';
private static final char WHITE = 'O';
private static boolean blackTurn = true;
public static void main(String[] args) {
initializeBoard();
displayBoard();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(getCurrentPlayer() + " player's turn. Enter row and column (e.g. '3 4'): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (isValidMove(row, col)) {
makeMove(row, col);
displayBoard();
if (isGameOver(row, col)) {
break;
}
blackTurn = !blackTurn;
} else {
System.out.println("Invalid move. Try again.");
}
}
System.out.println(getCurrentPlayer() + " player wins!");
}
private static void initializeBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '-';
}
}
}
private static void displayBoard() {
System.out.print(" ");
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < BOARD_SIZE; i++) {
System.out.print(i + " ");
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private static char getCurrentPlayer() {
return blackTurn ? BLACK : WHITE;
}
private static boolean isValidMove(int row, int col) {
if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
return false;
}
return board[row][col] == '-';
}
private static void makeMove(int row, int col) {
board[row][col] = getCurrentPlayer();
}
private static boolean isGameOver(int row, int col) {
return isHorizontalWin(row) || isVerticalWin(col) || isDiagonalWin(row, col);
}
private static boolean isHorizontalWin(int row) {
int count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[row][i] == getCurrentPlayer()) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
private static boolean isVerticalWin(int col) {
int count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][col] == getCurrentPlayer()) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
private static boolean isDiagonalWin(int row, int col) {
int count = 0;
int i = row, j = col;
while (i >= 0 && j >= 0 && board[i][j] == getCurrentPlayer()) {
count++;
i--;
j--;
}
i = row + 1;
j = col + 1;
while (i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == getCurrentPlayer()) {
count++;
i++;
j++;
}
if (count >= 5) {
return true;
}
count = 0;
i = row;
j = col;
while (i >= 0 && j < BOARD_SIZE && board[i][j] == getCurrentPlayer()) {
count++;
i--;
j++;
}
i = row + 1;
j = col - 1;
while (i < BOARD_SIZE && j >= 0 && board[i][j] == getCurrentPlayer()) {
count++;
i++;
j--;
}
return count >= 5;
}
}
```
这个示例使用一个二维字符数组来表示棋盘,其中 `'-'` 表示空格,`'X'` 表示黑棋,`'O'` 表示白棋。程序会交替让黑棋和白棋下棋,直到有一方胜利。胜利的条件是其中一方在横、竖、斜方向上连成五个棋子。