用java编程双人五子棋
时间: 2024-06-14 08:05:09 浏览: 211
以下是一个用Java编写的双人五子棋游戏的示例代码:
```java
import java.util.Scanner;
public class GomokuGame {
private char[][] board;
private char currentPlayer;
private boolean isGameOver;
public GomokuGame() {
board = new char[15][15];
currentPlayer = 'X';
isGameOver = false;
initializeBoard();
}
private void initializeBoard() {
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
board[i][j] = '-';
}
}
}
public void playGame() {
Scanner scanner = new Scanner(System.in);
while (!isGameOver) {
System.out.println("Player " + currentPlayer + ", enter your move (row and column):");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (isValidMove(row, col)) {
makeMove(row, col);
printBoard();
checkWin(row, col);
switchPlayer();
} else {
System.out.println("Invalid move. Try again.");
}
}
scanner.close();
}
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 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 void checkWin(int row, int col) {
if (checkHorizontal(row) || checkVertical(col) || checkDiagonal(row, col)) {
System.out.println("Player " + currentPlayer + " wins!");
isGameOver = true;
}
}
private boolean checkHorizontal(int row) {
int count = 0;
for (int i = 0; i < 15; i++) {
if (board[row][i] == currentPlayer) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
private boolean checkVertical(int col) {
int count = 0;
for (int i = 0; i < 15; i++) {
if (board[i][col] == currentPlayer) {
count++;
if (count == 5) {
return true;
}
} else {
count = 0;
}
}
return false;
}
private boolean checkDiagonal(int row, int col) {
int count = 0;
int i = row;
int j = col;
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 = 0;
i = row;
j = col;
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;
}
private void switchPlayer() {
currentPlayer = currentPlayer == 'X' ? 'O' : 'X';
}
public static void main(String[] args) {
GomokuGame game = new GomokuGame();
game.playGame();
}
}
```
阅读全文