#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10 // 扫雷地图大小
#define BOMBS 10 // 地雷数量
int board[SIZE][SIZE]; // 扫雷地图
int uncover[SIZE][SIZE]; // 标记是否被翻开,1表示已翻开,0表示未翻开
void initBoard() {
// 初始化地图
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = 0; // 0表示没有地雷
uncover[i][j] = 0; // 初始时所有格子未翻开
}
}
}
void printBoard() {
// 打印地图
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (uncover[i][j]) {
if (board[i][j] == -1) {
printf("* "); // 地雷
} else {
printf("%d ", board[i][j]); // 数字
}
} else {
printf(". "); // 未翻开
}
}
printf("\n");
}
printf("\n");
}
void generateBombs() {
// 生成地雷
int count = 0;
while (count < BOMBS) {
int row = rand() % SIZE;
int col = rand() % SIZE;
if (board[row][col] != -1) {
board[row][col] = -1;
count++;
}
}
}
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;
}
}
}
}
int main() {
srand(time(0)); // 设置随机种子
initBoard();
generateBombs();
calculateNumbers();
int row, col;
while (1) {
printBoard();
printf("请输入要翻开的格子的行号和列号(范围:0-%d):", SIZE - 1);
scanf("%d %d", &row, &col);
if (row >= 0 && row < SIZE && col >= 0 && col < SIZE) {
uncover[row][col] = 1; // 标记为已翻开
if (board[row][col] == -1) {
printf("你被炸死了!游戏结束!\n");
break;
} else if (board[row][col] > 0) {
printf("你翻开了一个数字:%d\n", board[row][col]);
} else {
printf("你翻开了一个空白格子,请继续探索!\n");
}
} else {
printf("输入的格子位置不合法,请重新输入!\n");
}
}
return 0;
}