JAVA写Hex游戏代码
时间: 2024-03-18 13:16:44 浏览: 22
以下是一个简单的Java代码,实现了Hex游戏的基本功能:
```java
import java.util.Scanner;
public class HexGame {
private int size; // 棋盘大小
private char[][] board; // 棋盘
private char currentPlayer; // 当前玩家
public HexGame(int size) {
this.size = size;
board = new char[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
board[row][col] = '-';
}
}
currentPlayer = 'X';
}
public void play() {
Scanner scanner = new Scanner(System.in);
boolean gameOver = false;
while (!gameOver) {
// 打印棋盘
printBoard();
// 玩家下棋
System.out.print("Player " + currentPlayer + ", enter row and column: ");
int row = scanner.nextInt();
int col = scanner.nextInt();
while (row < 0 || row >= size || col < 0 || col >= size || board[row][col] != '-') {
System.out.print("Invalid move, try again: ");
row = scanner.nextInt();
col = scanner.nextInt();
}
board[row][col] = currentPlayer;
// 判断胜负
if (isWin()) {
System.out.println("Player " + currentPlayer + " wins!");
gameOver = true;
} else if (isTie()) {
System.out.println("Tie game.");
gameOver = true;
} else {
currentPlayer = currentPlayer == 'X' ? 'O' : 'X';
}
}
}
private boolean isWin() {
// TODO: 实现判断胜负的逻辑
return false;
}
private boolean isTie() {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (board[row][col] == '-') {
return false;
}
}
}
return true;
}
private void printBoard() {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
HexGame game = new HexGame(5);
game.play();
}
}
```
注意,这个代码中的 `isWin` 方法还没有实现,需要根据实际的游戏规则来实现。你可以根据自己的需要修改代码,并添加更多的功能。