package saolei;
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
private int[][] board;
private boolean[][] revealed;
private int size;
private int numMines;
public Minesweeper(int size, int numMines) {
this.size = size;
this.numMines = numMines;
this.board = new int[size][size];
this.revealed = new boolean[size][size];
initializeBoard();
placeMines();
calculateNumbers();
}
private void initializeBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = 0;
revealed[i][j] = false;
}
}
}
private void placeMines() {
Random random = new Random();
int count = 0;
while (count < numMines) {
int row = random.nextInt(size);
int col = random.nextInt(size);
if (board[row][col] != -1) {
board[row][col] = -1;
count++;
}
}
}
private void calculateNumbers() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (board[i][j] != -1) {
int count = 0;
if (i > 0 && j > 0 && board[i - 1][j - 1] == -1) count++;
if (i > 0 && board[i - 1][j] == -1) count++;
if (i > 0 && j < size - 1 && board[i - 1][j + 1] == -1) count++;
if (j > 0 && board[i][j - 1] == -1) count++;
if (j < size - 1 && board[i][j + 1] == -1) count++;
if (i < size - 1 && j > 0 && board[i + 1][j - 1] == -1) count++;
if (i < size - 1 && board[i + 1][j] == -1) count++;
if (i < size - 1 && j < size - 1 && board[i + 1][j + 1] == -1) count++;
board[i][j] = count;
}
}
}
}
public void revealCell(int row, int col) {
if (row < 0 || row >= size || col < 0 || col >= size) {
System.out.println("无效单元格!");
return;
}
if (revealed[row][col]) {
System.out.println("细胞已经暴露!");
return;
}
revealed[row][col] = true;
if (board[row][col] == -1) {
System.out.println("游戏结束!你触雷了.");
return;
}
if (board[row][col] == 0) {
revealNeighbors(row, col);
}
}
private void revealNeighbors(int row, int col) {
if (row > 0 && col > 0 && !revealed[row - 1][col - 1]) {
revealed[row - 1][col - 1] = true;
if (board[row - 1][col - 1] == 0) {
revealNeighbors(row - 1, col - 1);
}
}
// Check and reveal other neighbors...
}
public void printBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (revealed[i][j]) {
if (board[i][j] == -1) {
System.out.print("* ");
} else {
System.out.print(board[i][j] + " ");
}
} else {
System.out.print(". ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("输入版的大小: ");
int size = scanner.nextInt();
System.out.print("输入地雷数量: ");
int numMines = scanner.nextInt();
Minesweeper game = new Minesweeper(size, numMines);
while (true) {
System.out.print("输入要显示的行和列(用空格隔出): ");
int row = scanner.nextInt();
int col = scanner.nextInt();
game.revealCell(row, col);
game.printBoard();
}
}
}