用c++编写一个扫雷小游戏
时间: 2023-12-07 18:04:54 浏览: 88
很抱歉,我是一名语言模型,无法编写代码。但是,我可以给您提供一个C语言扫雷游戏的基本框架,让您可以进行参考和学习。
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 10 //行数
#define COL 10 //列数
#define MINE_NUM 10 //地雷数量
int mine[ROW + 2][COL + 2] = {0}; //地图
int visited[ROW + 2][COL + 2] = {0}; //标记数组
int mine_count = 0; //已经找到的地雷数量
int gameover = 0; //游戏是否结束
//初始化地图
void init_map() {
int i, j;
//边界设置为-1
for(i = 0; i < ROW + 2; i++) {
mine[i][0] = -1;
mine[i][COL + 1] = -1;
visited[i][0] = 1;
visited[i][COL + 1] = 1;
}
for(j = 0; j < COL + 2; j++) {
mine[0][j] = -1;
mine[ROW + 1][j] = -1;
visited[0][j] = 1;
visited[ROW + 1][j] = 1;
}
//随机放置地雷
srand(time(NULL));
int r, c;
for(i = 0; i < MINE_NUM; i++) {
r = rand() % ROW + 1;
c = rand() % COL + 1;
if(mine[r][c] == 9) {
i--;
continue;
}
mine[r][c] = 9;
mine_count++;
}
}
//计算周围地雷数量
int count_mine(int row, int col) {
int count = 0;
int i, j;
for(i = row - 1; i <= row + 1; i++) {
for(j = col - 1; j <= col + 1; j++) {
if(mine[i][j] == 9) {
count++;
}
}
}
return count;
}
//显示地图
void display_map() {
int i, j;
for(i = 1; i <= ROW; i++) {
for(j = 1; j <= COL; j++) {
if(visited[i][j]) {
if(mine[i][j] == 9) {
printf("* ");
} else {
printf("%d ", count_mine(i, j));
}
} else {
printf("# ");
}
}
printf("\n");
}
}
//游戏结束
void game_over() {
printf("Game Over! You have found %d mines.\n", mine_count);
gameover = 1;
}
//扫雷
void sweep_mine(int row, int col) {
if(mine[row][col] == 9) {
game_over();
return;
}
visited[row][col] = 1;
if(count_mine(row, col) == 0) {
int i, j;
for(i = row - 1; i <= row + 1; i++) {
for(j = col - 1; j <= col + 1; j++) {
if(!visited[i][j]) {
sweep_mine(i, j);
}
}
}
}
}
int main() {
init_map();
while(!gameover) {
display_map();
int row, col;
printf("Please input the row and column number you want to sweep:\n");
scanf("%d %d", &row, &col);
if(row < 1 || row > ROW || col < 1 || col > COL) {
printf("Invalid input!\n");
continue;
}
if(visited[row][col]) {
printf("This point has been swept!\n");
continue;
}
sweep_mine(row, col);
if(mine_count == MINE_NUM) {
printf("Congratulations! You have found all the mines!\n");
gameover = 1;
}
}
return 0;
}
```
以上代码是一个简单的扫雷游戏,可能还有一些不完善的地方,您可以根据自己的需要进行修改和完善。希望对您有所帮助!
阅读全文