使用C语言设计扫雷游戏
设计扫雷游戏是一个很有趣的项目,以下是一个使用C语言设计扫雷游戏的简单示例:
```c #include <stdio.h> #include <stdlib.h> #include <time.h>
#define SIZE 10 #define MINES 10
int field[SIZE][SIZE]; int revealed[SIZE][SIZE];
void initializeField() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { field[i][j] = 0; revealed[i][j] = 0; } } }
void plantMines() { srand(time(NULL));
int count = 0;
while (count < MINES) {
int x = rand() % SIZE;
int y = rand() % SIZE;
if (field[x][y] != -1) {
field[x][y] = -1;
count++;
}
}
}
void printField() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (revealed[i][j]) { if (field[i][j] == -1) { printf("* "); } else { printf("%d ", field[i][j]); } } else { printf(". "); } } printf("\n"); } }
int countMines(int x, int y) { int count = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < SIZE && j >= 0 && j < SIZE) {
if (field[i][j] == -1) {
count++;
}
}
}
}
return count;
}
void reveal(int x, int y) { if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) { return; }
if (revealed[x][y]) {
return;
}
revealed[x][y] = 1;
if (field[x][y] == 0) {
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
reveal(i, j);
}
}
}
}
int main() { initializeField(); plantMines();
int gameOver = 0;
while (!gameOver) {
printField();
int x, y;
printf("Enter the coordinates (x y): ");
scanf("%d %d", &x, &y);
if (field[x][y] == -1) {
printf("Game Over!\n");
gameOver = 1;
} else {
revealed[x][y] = 1;
reveal(x, y);
}
}
return 0;***
相关推荐














