打一个超级简单的c语言扫雷程序
时间: 2023-08-07 07:05:06 浏览: 54
好的,下面是一个非常简单的C语言扫雷程序,其中只实现了最基本的功能,适合初学者参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define MINES 10
int main() {
int board[ROWS][COLS]; // 游戏棋盘
int mines[MINES][2]; // 地雷位置
int i, j, k, x, y, count;
char input[10];
// 初始化棋盘
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
board[i][j] = 0;
}
}
// 初始化地雷
srand(time(NULL));
for (k = 0; k < MINES; k++) {
do {
x = rand() % ROWS;
y = rand() % COLS;
} while (board[x][y] == -1);
board[x][y] = -1;
mines[k][0] = x;
mines[k][1] = y;
}
// 主循环
while (1) {
// 显示棋盘
printf(" ");
for (j = 0; j < COLS; j++) {
printf("%2d ", j);
}
printf("\n");
for (i = 0; i < ROWS; i++) {
printf("%2d ", i);
for (j = 0; j < COLS; j++) {
if (board[i][j] >= 0) {
printf(" - ");
} else {
printf(" * ");
}
}
printf("\n");
}
// 读取玩家输入
printf("\nEnter row and column (e.g. 3 4), or q to quit: ");
fgets(input, 10, stdin);
if (input[0] == 'q') {
break;
}
sscanf(input, "%d %d", &x, &y);
// 检查输入是否合法
if (x < 0 || x >= ROWS || y < 0 || y >= COLS) {
printf("Invalid input!\n");
continue;
}
if (board[x][y] >= 0) {
printf("Already opened!\n");
continue;
}
// 判断是否踩到地雷
if (board[x][y] == -1) {
printf("Oops, you stepped on a mine!\n");
break;
}
// 计算周围地雷数量
count = 0;
for (i = x-1; i <= x+1; i++) {
for (j = y-1; j <= y+1; j++) {
if (i >= 0 && i < ROWS && j >= 0 && j < COLS && board[i][j] == -1) {
count++;
}
}
}
// 更新棋盘状态
board[x][y] = count;
}
// 显示地雷位置
for (k = 0; k < MINES; k++) {
printf("Mine %d at (%d, %d)\n", k+1, mines[k][0], mines[k][1]);
}
return 0;
}
```
这个程序采用了二维数组来表示游戏棋盘,-1代表有地雷,0代表未翻开,1-8代表周围地雷数量。程序随机生成若干个地雷并在棋盘上标记出来,然后进入主循环,每次循环中读取玩家输入(选择翻开哪个方格),判断是否踩中地雷,如果没有踩中,则更新棋盘状态。玩家可以输入q来结束游戏。当游戏结束后,程序会显示地雷位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)