java五子棋游戏代码
时间: 2023-07-09 16:53:43 浏览: 105
以下是一个简单的Java五子棋游戏代码示例:
```
import java.util.Scanner;
public class Gobang {
public static final int BOARD_SIZE = 15;
public String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
public static final String PLAYER1 = "X";
public static final String PLAYER2 = "O";
public String currentPlayer;
public void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = "+";
}
}
}
public void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public boolean isBoardFull() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
if (board[i][j].equals("+")) {
return false;
}
}
}
return true;
}
public boolean isWinningMove(int row, int col) {
String player = board[row][col];
int count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[row][i].equals(player)) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
count = 0;
for (int i = 0; i < BOARD_SIZE; i++) {
if (board[i][col].equals(player)) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
count = 0;
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col + i;
if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE) {
if (board[r][c].equals(player)) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
}
count = 0;
for (int i = -4; i <= 4; i++) {
int r = row + i;
int c = col - i;
if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE) {
if (board[r][c].equals(player)) {
count++;
} else {
count = 0;
}
if (count == 5) {
return true;
}
}
}
return false;
}
public void play() {
initBoard();
currentPlayer = PLAYER1;
Scanner scanner = new Scanner(System.in);
while (true) {
printBoard();
System.out.print("Player " + currentPlayer + ", enter row number: ");
int row = scanner.nextInt();
System.out.print("Player " + currentPlayer + ", enter column number: ");
int col = scanner.nextInt();
if (board[row][col].equals("+")) {
board[row][col] = currentPlayer;
if (isWinningMove(row, col)) {
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
break;
} else if (isBoardFull()) {
printBoard();
System.out.println("Game is a tie!");
break;
} else {
if (currentPlayer.equals(PLAYER1)) {
currentPlayer = PLAYER2;
} else {
currentPlayer = PLAYER1;
}
}
} else {
System.out.println("That position is already taken. Try again.");
}
}
}
public static void main(String[] args) {
Gobang game = new Gobang();
game.play();
}
}
```
这个代码实现了一个交互式的五子棋游戏,玩家可以通过输入行和列号来下棋,程序会检查是否有五子连珠,以及棋盘是否已经下满,如果有则宣布胜者或平局。
阅读全文