写一个扫雷c语言代码出来可运行
时间: 2024-09-26 14:10:22 浏览: 27
当然可以。这是一个简单的 C 语言扫雷游戏的代码示例,它是一个命令行版的基本版本。请注意,由于字符界面限制,这个游戏不会像图形化界面那样友好,但它能让你理解基本的游戏规则。这个程序使用了二维数组表示雷区,并随机放置地雷。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10 // 雷区大小(行数)
#define COLS 10 // 雷区大小(列数)
#define BOMBS 10 // 地雷的数量
int grid[ROWS][COLS], revealed[ROWS][COLS] = {0}, bombs_placed = 0;
// 随机生成地雷
void place_bombs() {
srand(time(NULL));
for (int i = 0; i < BOMBS; ++i) {
int r = rand() % ROWS;
int c = rand() % COLS;
if (!revealed[r][c]) {
grid[r][c] = -1;
bombs_placed++;
}
}
}
// 检查周围是否有地雷
int check_adjacent(int r, int c) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue; // 自身不计数
if (i * i + j * j > 1) continue; // 禁止越界检查
if (revealed[r + i][c + j] && grid[r + i][c + j] == -1) {
count++;
}
}
}
return count;
}
// 主函数
int main() {
printf("Welcome to Minesweeper!\n");
place_bombs();
for (int r = 0; r < ROWS; ++r) {
for (int c = 0; c < COLS; ++c) {
if (grid[r][c] != -1) {
printf("%d ", grid[r][c]);
} else {
printf("* ");
}
}
printf("\n");
}
while (bombs_placed) {
int row, col;
printf("\nChoose a cell (row, column): ");
scanf("%d %d", &row, &col);
if (row >= 0 && row < ROWS && col >= 0 && col < COLS && !revealed[row][col]) {
revealed[row][col] = 1;
int mine_count = check_adjacent(row, col);
if (mine_count == 0) {
printf("Congratulations! You found a safe spot.\n");
bombs_placed--;
} else {
printf("Sorry, there are %d mines around here.\n", mine_count);
}
} else {
printf("Invalid move.\n");
}
}
printf("You won! All mines have been cleared.\n");
return 0;
}
```
阅读全文