使用c语言设计一个扫雷游戏
时间: 2023-12-24 07:03:32 浏览: 80
以下是使用C语言设计扫雷游戏的基本步骤:
1.定义游戏板块的大小和雷的数量。
2.创建游戏板块并在其中******则游戏胜利。
下面是一个简单的C语言扫雷游戏的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
int board[ROWS][COLS];
int visible[ROWS][COLS];
void init_board() {
int i, j, count = 0;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = 0;
visible[i][j] = 0;
}
}
srand(time(NULL));
while (count < MINES) {
int row = rand() % ROWS;
int col = rand() % COLS;
if (board[row][col] == 0) {
board[row][col] = 9;
count++;
}
}
}
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 (visible[i][j] == 0) {
printf(". ");
} else if (visible[i][j] == 1) {
printf("%d ", board[i][j]);
} else if (visible[i][j] == 2) {
printf("F ");
}
}
printf("\n");
}
}
int count_mines(int row, int col) {
int count = 0, 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 && board[i][j] == 9) {
count++;
}
}
}
return count;
}
void reveal(int row, int col) {
if (visible[row][col] == 1 || visible[row][col] == 2) {
return;
}
visible[row][col] = 1;
if (board[row][col] == 9) {
printf("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 flag(int row, int col) {
if (visible[row][col] == 0) {
visible[row][col] = 2;
} else if (visible[row][col] == 2) {
visible[row][col] = 0;
}
}
int check_win() {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (board[i][j] != 9 && visible[i][j] == 0) {
return 0;
}
}
}
return 1;
}
int main() {
init_board();
while (1) {
print_board();
if (check_win()) {
printf("You win!\n");
exit(0);
}
int row, col;
char action;
printf("Enter row and column (e.g. 3 4) or flag (e.g. f 3 4): ");
scanf("%c %d %d", &action, &row, &col);
getchar();
if (action == 'f') {
flag(row, col);
} else {
reveal(row, col);
}
}
return 0;
}
```
阅读全文