#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 5
#define MINES 5
char board[SIZE][SIZE];
int mines[SIZE][SIZE];
int revealed[SIZE][SIZE];
void initializeBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
board[i][j] = '-';
revealed[i][j] = 0;
}
}
for (int i = 0; i < MINES; i++) {
int x, y;
do {
} while (mines[x][y]);
mines[x][y] = 1;
}
}
void printBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
}
}
}
int countMines(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (x + i >= 0 && x + i < SIZE && y + j >= 0 && y + j < SIZE && mines[x + i][y + j]) {
count++;
}
}
}
return count;
}
void reveal(int x, int y) {
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE || revealed[x][y]) return;
revealed[x][y] = 1;
board[x][y] = (mines[x][y]) ? '*' : ' ';
if (countMines(x, y) > 0) {
board[x][y] = countMines(x, y) + '0';
} else {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
reveal(x + i, y + j);
}
}
}
}
int main() {
initializeBoard();
int x, y;
char input;
do {
printBoard();
scanf(" %c%c", &input
, &input
);
x = input - '0';
y = input - '0';
if (board[x][y] == '-') {
reveal(x, y);
}
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (mines[i][j] && revealed[i][j]) {
return 0;
}
}
}
} while (input == 'y' || input == 'Y');
return 0;
}
在这个代码中,SIZE定义了游戏的大小(5x5),MINES定义了雷的数量(5个)。board数组用于显示游戏界面,mines数组用于存储雷的位置,revealed数组用于跟踪哪些格子已经被揭示。
initializeBoard函数初始化游戏板,printBoard函数打印游戏板,countMines函数计算给定位置周围的雷的数量,reveal函数揭示一个格子及其周围的非雷格子。