可以玩扫雷的C语言代码
时间: 2023-12-03 20:33:12 浏览: 67
扫雷C语言代码
5星 · 资源好评率100%
以下是一个简单的扫雷游戏的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
int board[ROWS][COLS];
int revealed[ROWS][COLS];
int mines_found = 0;
//初始化游戏面板,将所有方格设置为未揭示状态
void init_board() {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = 0;
revealed[i][j] = 0;
}
}
}
//随机设置地雷
void set_mines() {
int i, j, count = 0;
while (count < MINES) {
i = rand() % ROWS;
j = rand() % COLS;
if (board[i][j] != -1) {
board[i][j] = -1;
count++;
}
}
}
//计算周围地雷数量
int count_mines(int row, int col) {
int i, j, count = 0;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == -1) {
count++;
}
}
}
return count;
}
//揭示一个方格并递归揭示周围方格
void reveal(int row, int col) {
if (revealed[row][col]) {
return;
}
revealed[row][col] = 1;
if (board[row][col] == -1) {
printf("BOOM! Game over.\n");
exit(0);
}
if (count_mines(row, col) == 0) {
int i, j;
for (i = row - 1; i <= row + 1; i++) {
for (j = col - 1; j <= col + 1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS) {
reveal(i, j);
}
}
}
}
}
//打印游戏面板
void print_board() {
int i, j;
printf(" ");
for (i = 0; i < COLS; i++) {
printf("%d ", i);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%d ", i);
for (j = 0; j < COLS; j++) {
if (revealed[i][j]) {
if (board[i][j] == -1) {
printf("* ");
} else {
printf("%d ", count_mines(i, j));
}
} else {
printf(". ");
}
}
printf("\n");
}
}
int main() {
srand(time(NULL));
init_board();
set_mines();
while (mines_found < MINES) {
print_board();
int row, col;
printf("Enter row and column (e.g. 2 3): ");
scanf("%d %d", &row, &col);
if (row >= ROWS || col >= COLS) {
printf("Invalid input. Try again.\n");
continue;
}
if (revealed[row][col]) {
printf("Already revealed. Try again.\n");
continue;
}
reveal(row, col);
if (board[row][col] == -1) {
mines_found++;
}
}
printf("Congratulations! You found all the mines.\n");
return 0;
}
```
该程序使用二维数组表示游戏面板,其中-1表示地雷,其他数字表示周围的地雷数。游戏开始时,程序初始化面板并随机设置地雷位置。玩家可以输入行和列来揭示一个方格,程序将计算周围地雷数量并递归揭示周围的方格。如果揭示到地雷,玩家将输掉游戏。如果玩家成功揭示所有地雷,游戏结束并显示祝贺消息。
阅读全文