• 前言
• 一、初始化菜单
• 二、初始化棋盘
• 三、棋盘的打印
• 四、布置雷
• 五、排查雷
• 六、主函数
• 总结

# 前言

`今天来描述我们常见的扫雷游戏，我们用到的核心思想是二维数组，判断语句和循环语句，和上次一样我们也是分别创建了3个文件：Game.h，Game.c，test.c`

1代表这个格子附近一圈有1个雷

# 一、初始化菜单

``````void menu() {

printf("*****************************\n");
printf("********** 1.play   *********\n");
printf("********** 2.exit   *********\n");
printf("*****************************\n");
}
``````

# 二、初始化棋盘

``````//在这里我们多给了一个参数如果是内部棋盘 set为0，并且全部初始化为0
//展示棋盘 给出参数set为* 棋盘全部初始化为*
void InitBoard(char board[ROWS][COLS], int rows, int cols,char set)
{
int i = 0;
int j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
``````

# 三、棋盘的打印

``````void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
int i = 0;
int j = 0;
printf("--------------------扫雷游戏-------------------\n");
for (j = 0; j <= col; j++)
{
printf("%d ", j);
}
printf("\n");
for (i = 1; i <= row; i++)
{
printf("%d ",i);
for (j = 1; j <= col; j++)
{
printf("%c ",board[i][j]);
}
printf("\n");
}
printf("--------------------扫雷游戏-------------------\n");
}
``````

# 四、布置雷

``````void SetMine(char board[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
//横 1~9
//纵 1~9
while (count) {
int x = rand() % row + 1;//rand%row为0-8  +1的话范围是1-9
int y = rand() % col + 1;//同理
if (board[x][y] == '0')
{
board[x][y] = '1';
count--;
}
}
}
``````

# 五、排查雷

``````int get_mine_count(char board[ROWS][COLS],int row,int col)
{
int  sum = 0;
for (int i = ROW - 1; i <= ROW + 1; i++)
{
for (int j = COL - 1; j <= COL + 1; j++)
{
sum += board[i][j] - '0';
}
}
return sum;
}
``````

get_mine_count()函数利用周围一圈加起来的总和为几，则附近一圈有多少雷.

``````void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS], int row, int col)
{
int x = 0, y = 0;
int win = 0;//找到非雷的个数
while (win<row*col-EASY_COUNT)//遍历的步数小于雷数，则证明扫雷成功
{
printf("请输入要排查的坐标->");
scanf("%d %d", &x, &y);
if (x >= 1 && x <= row && y >= 1 && y <= col)//放置数组越界
{
if (show[x][y] != '*')
{
printf("该坐标已经被排查过了，请重新输入坐标\n");
}
else
{
if (mine[x][y] == 1)
{
printf("很遗憾，你被炸死了\n");
DisplayBoard(mine, ROW, COL);
break;
}
else
{
win++;
//统计mine数组中x,y坐标周围有几个雷
int count = get_mine_count(mine, row, col);
show[x][y] = count + '0';//转化成数字字符
DisplayBoard(show, ROW, COL);
}
}
}
else
{
printf("输入的坐标非法，请重新输入\n");
}
}
if (win == row * col - EASY_COUNT)
{
printf("恭喜你，排雷成功\n");
DisplayBoard(mine,row,col);
}
}
``````

# 六、主函数

``````int main() {
int input=0;
//设置随机数的生成起点
srand((unsigned int)time(NULL));
do
{
printf("请选择->");
scanf("%d",&input);
switch (input) {
case 1:
printf("扫雷\n");
Game();
break;
case 0:
printf("退出游戏\n");
break;
default:
printf("输入错误，请重新输入\n");
break;
}
}
while(input);
return 0;
}
``````