package game;
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private int[][] board; // 扫雷面板
private boolean[][] revealed; // 已经翻开的方块
private final int mineCount; // 总雷数
private int remainingMines; // 剩余雷数
private boolean gameEnd; // 游戏是否结束
public Minesweeper(int rows, int cols, int mineCount) {
this.board = new int[rows][cols];
this.revealed = new boolean[rows][cols];
this.mineCount = mineCount;
this.remainingMines = mineCount;
this.gameEnd = false;
setMines();
setNumber();
}
// 随机设置雷
private void setMines() {
Random random = new Random();
int count = 0;
while (count < mineCount) {
int row = random.nextInt(board.length);
int col = random.nextInt(board[0].length);
if (board[row][col] != -1) {
board[row][col] = -1;
count++;
}
}
}
// 设置数字(表示周围的雷数)
private void setNumber() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == -1) {
continue;
}
int count = 0;
for (int r = i - 1; r <= i + 1; r++) {
for (int c = j - 1; c <= j + 1; c++) {
if (r >= 0 && r < board.length && c >= 0 && c < board[0].length && board[r][c] == -1) {
count++;
}
}
}
board[i][j] = count;
}
}
}
// 输出当前局面
public void printBoard() {
System.out.print(" ");
for (int i = 0; i < board[0].length; i++) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.print(i + " ");
for (int j = 0; j < board[0].length; j++) {
if (!revealed[i][j]) {
System.out.print("* ");
} else if (board[i][j] == -1) {
System.out.print("X ");
} else {
System.out.print(board[i][j] + " ");
}
}
System.out.println();
}
}
// 翻开指定位置的方块,并判断游戏是否结束
private void reveal(int row, int col) {
if (revealed[row][col]) {
return;
}
revealed[row][col] = true;
if (board[row][col] == -1) {
gameEnd = true;
System.out.println("很遗憾,你输了!");
return;
}
if (--remainingMines == 0) {
gameEnd = true;
System.out.println("恭喜你,你赢了!");
return;
}
if (board[row][col] == 0) {
for (int r = row - 1; r <= row + 1; r++) {
for (int c = col - 1; c <= col + 1; c++) {
if (r >= 0 && r < board.length && c >= 0 && c < board[0].length) {
reveal(r, c);
}
}
}
}
}
// 开始游戏
public void play() {
Scanner scanner = new Scanner(System.in);
while (!gameEnd) {
System.out.println("当前雷数:" + remainingMines);
printBoard();
System.out.println("请输入行列坐标(用空格分隔):");
int row = scanner.nextInt();
int col = scanner.nextInt();
if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) {
System.out.println("输入不合法,请重新输入!");
continue;
}
reveal(row, col);
}
scanner.close();
}
public static void main(String[] args) {
Minesweeper game = new Minesweeper(10, 10, 10);
game.play();
}
}