五子棋游戏java简洁
时间: 2024-01-12 12:22:07 浏览: 23
以下是一个简洁的五子棋游戏的Java代码示例:
```java
import java.util.Scanner;
public class GomokuGame {
private char[][] board;
private char currentPlayer;
private boolean gameOver;
public GomokuGame() {
board = new char[15][15];
currentPlayer = 'X';
gameOver = false;
initializeBoard();
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
System.out.println("当前玩家:" + currentPlayer);
System.out.print("请输入要下棋的行号和列号(以空格分隔):");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (isValidMove(row, col)) {
makeMove(row, col);
printBoard();
checkWin(row, col);
switchPlayer();
} else {
System.out.println("无效的移动,请重新输入!");
}
}
scanner.close();
}
private void initializeBoard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = '-';
}
}
}
private void printBoard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private boolean isValidMove(int row, int col) {
return row >= 0 && row < 15 && col >= 0 && col < 15 && board[row][col] == '-';
}
private void makeMove(int row, int col) {
board[row][col] = currentPlayer;
}
private void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
private void checkWin(int row, int col) {
if (checkHorizontal(row, col) || checkVertical(row, col) || checkDiagonal(row, col)) {
System.out.println("玩家 " + currentPlayer + " 获胜!");
gameOver = true;
}
}
private boolean checkHorizontal(int row, int col) {
int count = 1;
int i = col - 1;
while (i >= 0 && board[row][i] == currentPlayer) {
count++;
i--;
}
i = col + 1;
while (i < 15 && board[row][i] == currentPlayer) {
count++;
i++;
}
return count >= 5;
}
private boolean checkVertical(int row, int col) {
int count = 1;
int i = row - 1;
while (i >= 0 && board[i][col] == currentPlayer) {
count++;
i--;
}
i = row + 1;
while (i < 15 && board[i][col] == currentPlayer) {
count++;
i++;
}
return count >= 5;
}
private boolean checkDiagonal(int row, int col) {
int count = 1;
int i = row - 1;
int j = col - 1;
while (i >= 0 && j >= 0 && board[i][j] == currentPlayer) {
count++;
i--;
j--;
}
i = row + 1;
j = col + 1;
while (i < 15 && j < 15 && board[i][j] == currentPlayer) {
count++;
i++;
j++;
}
if (count >= 5) {
return true;
}
count = 1;
i = row - 1;
j = col + 1;
while (i >= 0 && j < 15 && board[i][j] == currentPlayer) {
count++;
i--;
j++;
}
i = row + 1;
j = col - 1;
while (i < 15 && j >= 0 && board[i][j] == currentPlayer) {
count++;
i++;
j--;
}
return count >= 5;
}
}
public class Main {
public static void main(String[] args) {
GomokuGame game = new GomokuGame();
game.playGame();
}
}
```