java单人五子棋类图
时间: 2023-09-14 10:03:28 浏览: 44
你好!这是一个关于Java实现的单人五子棋游戏的示例代码:
```java
import java.util.Scanner;
public class SinglePlayerGomoku {
private static final int SIZE = 15;
private static final char EMPTY = '-'; private static final char PLAYER = 'X';
private static final char COMPUTER = 'O';
private char[][] board;
private Scanner scanner;
public SinglePlayerGomoku() {
board = new char[SIZE][SIZE];
scanner = new Scanner(System.in);
initializeBoard();
}
private void initializeBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = EMPTY;
}
}
}
private void printBoard() {
System.out.print(" ");
for (int i = 0; i < SIZE; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < SIZE; i++) {
System.out.print(i + " ");
for (int j = 0; j < SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
private boolean makeMove(int row, int col, char player) {
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != EMPTY) {
return false;
}
board[row][col] = player;
return true;
}
private boolean isBoardFull() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (board[i][j] == EMPTY) {
return false;
}
}
}
return true;
}
private boolean hasWon(int row, int col, char player) {
// Check horizontally
int count = 0;
int i = col;
while (i >= 0 && board[row][i] == player) {
count++;
i--;
}
i = col + 1;
while (i < SIZE && board[row][i] == player) {
count++;
i++;
}
if (count >= 5) {
return true;
}
// Check vertically
count = 0;
int j = row;
while (j >= 0 && board[j][col] == player) {
count++;
j--;
}
j = row + 1;
while (j < SIZE && board[j][col] == player) {
count++;
j++;
}
if (count >= 5) {
return true;
}
// Check diagonally (top-left to bottom-right)
count = 0;
i = col;
j = row;
while (i >= 0 && j >= 0 && board[j][i] == player) {
count++;
i--;
j--;
}
i = col + 1;
j = row + 1;
while (i < SIZE && j < SIZE && board[j][i] == player) {
count++;
i++;
j++;
}
if (count >= 5) {
return true;
}
// Check diagonally (bottom-left to top-right)
count = 0;
i = col;
j = row;
while (i >= 0 && j < SIZE && board[j][i] == player) {
count++;
i--;
j++;
}
i = col + 1;
j = row - 1;
while (i < SIZE && j >= 0 && board[j][i] == player) {
count++;
i++;
j--;
}
return count >= 5;
}
private void play() {
int row, col;
boolean validMove;
boolean gameOver = false;
while (!gameOver) {
// Player's turn
System.out.print("Enter your move (row column): ");
row = scanner.nextInt();
col = scanner.nextInt();
validMove = makeMove(row, col, PLA