1.创建主函数、头文件
#pragma once
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define ROWS ROW+2
#define COLS COL+2
#define EASY_COUNT 10
#define ROW 9
#define COL 9
//初始化数组
void Initboard(char board[ROWS][COLS], int rows, int cols, char set);
//打印棋盘
void Display_board(char board[ROWS][COLS], int row, int col);
//布置雷
void Setmine(char mine[ROWS][COLS], int row, int col);
//排雷
void Findmine(char mine, int rows, int cols);
int main()
{
test();
return 0;
}
2.构建test函数
void menu()
{
printf("****************************\n");
printf("****** 1.开始游戏 ******\n");
printf("****** 2.退出游戏 ******\n");
printf("****************************\n");
}
void test()
{
int input = 0;
do
{
menu();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 2:
printf("已经退出游戏!\n");
break;
default:
printf("输入错误,请重新选择:");
break;
}
} while (input);
}
3.实现game函数
void game()
{
srand((unsigned int)time(NULL));//布雷的时候产生随机雷
//创建数组
char mine[ROWS][COLS] = { 0 };
char show[ROWS][COLS] = { 0 };
//初始化数组
Initboard(mine, ROWS, COLS, '0');//要注意传的字符是不一样的,布置雷的棋盘初始化为‘0’
Initboard(show, ROWS, COLS, '*');//用来显示的棋盘初始化为‘*’
//布置雷
Setmine(mine, ROW, COL);
//打印棋盘
//Display_board(mine, ROW, COL);//可以用来检测雷是否布置好
Display_board(show, ROW, COL);
//排雷
Findmine(mine,show, ROW, COL);
}
4.创建数组
//初始化数组
Initboard(mine, ROWS, COLS, '0');
Initboard(show, ROWS, COLS, '*');
5.初始化棋盘
void Initboard(char board[ROWS][COLS], int rows, int cols, char set)
{
int i = 0, j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
board[i][j] = set;
}
}
}
6.布置雷
void Setmine(char mine[ROWS][COLS], int row, int col)
{
int count = EASY_COUNT;
while (count)
{
int x = rand() % row + 1;
int y = rand() % col + 1;
if (mine[x][y] == '0')
{
mine[x][y] = '1';//随机布雷
count--;
}
}
}
7.打印棋盘
void Display_board(char board[ROWS][COLS], int row, int col)
{
int i = 0, j = 0;
//顺便打印出棋盘的行列号,方便输入
//打印行号
for (i = 0; i <= col; i++)
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i <= row; i++)
{
//打印列号
printf("%d ", i);
for (j = 1; j <= col; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");//记得换行
}
}
8.排雷
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 (mine[x][y] == '1')
{
printf("很遗憾,你被炸死了!\n");
Display_board(mine, ROW, COL);
break;
}
else
{
//计算坐标周围有几个雷
int n = get_mine_count(mine, x, y);
show[x][y] = n + '0';//显示的棋盘是字符
Display_board(show, ROW, COL);
win++;
}
}
else
{
printf("输入错误,请重新输入:");
}
}
if (win == row * col - EASY_COUNT)
{
printf("恭喜你,排雷成功!\n");
Display_board(mine, ROW, COL);
}
}
9.计算周围的雷
int get_mine_count(char mine[ROWS][COLS], int x, int y)
{
return mine[x - 1][y] +
mine[x - 1][y - 1] +
mine[x][y - 1] +
mine[x + 1][y - 1] +
mine[x + 1][y] +
mine[x + 1][y + 1] +
mine[x][y + 1] +
mine[x - 1][y + 1]-8*'0';//我们知道每个数字字符减去字符‘0’得到它本来的值(阿拉伯值),而周围一共八个格子,所以要乘以8,最后返回的是它算出的雷的个数
}