在进行扫雷游戏时,因为需要布雷,雷不可以显示出来;所以需要再定义一个数组,来显示游戏界面。mine[]和show[]
1.进入主函数开始游戏;game()
2.游戏中需要进行三个环节,
布雷:set_mine() 此函数要用到mine[]数组
打印雷阵:display()此函数要用到show[]数组
开始扫雷:sweep() 函数两个数组都要用到,mine[]数组要检测是否有雷,show[]要显示没雷的周围的个数
num_mine() 计算雷的个数
头文件
#include <stdio.h>
#define row 10
#define col 10
#define rows 11
#define cols 11
#include <time.h>
#include <string.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS 1
void menu();
void game(char mine[rows][cols], char show[rows][cols]);
void display(char show[rows][cols]);
void set_mine(char mine[rows][cols]);
int sweep(char mine[rows][cols], char show[rows][cols]);
int num_mine(char mine[rows][cols], int x, int y);
game.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "game.h"
void game(char mine[rows][cols], char show[rows][cols])
{
set_mine(mine);//布雷
display(show);//打印出每次操作完之后显示的雷阵
sweep(mine, show);//扫雷
}
void set_mine(char mine[rows][cols])//布雷,但是不打印,相当于隐藏雷
{
int i = 0;
int j = 0;
int x = 0;
srand((unsigned)time(NULL));//电脑产生随机数,作为
for (x = 1; x < rows; x++)//一共要布10个雷
{
i = rand() % row + 1;
j = rand() % col + 1;
if (mine[i][j] == '*')//如果所在的位置是*,说明此处可以布雷
{
mine[i][j] == '1';//将有雷的地方标记为1,以便排雷时使用
}
}
}
int sweep(char mine[rows][cols], char show[rows][cols])//扫雷,开始游戏
{
int count = 0;
int x = 0;
int y = 0;
printf("请输入坐标\n");
scanf("%d %d", &x, &y);
while (count <11)
{
if (mine[x][y] == '1')//如果为1,则表示雷
{
printf("你踩到雷了");
}
else if (mine[x][y] !='1')//如果不是1,则计算周围雷的个数
{
int tmp = num_mine(mine, x, y);
show[x][y] = tmp+‘0’;
count++;
}
}
printf("恭喜你,扫雷成功!");
display(show);
return 0;
}
int num_mine(char mine[rows][cols], int x, int y)//计算在输入坐标后周围的雷的个数
{
int count = 0;
if (mine[x - 1][y - 1] == '1')//左上方的位置
{
count++;
}
if (mine[x - 1][y] == '1')//正上方
count++;
if (mine[x - 1][y + 1] == '1')//右上方
count++;
if (mine[x][y - 1] == '1')//左边
count++;
if (mine[x][y + 1] == '1')//右边
count++;
if (mine[x + 1][y - 1] == '1')//左下方
count++;
if (mine[x + 1][y] == '1');//下方
count++;
if (mine[x + 1][y + 1] == '1')//右下方
{
count++;
}
return count;
}
void display(char show[rows][cols])//显示每次操作完之后的游戏界面
{
int i = 0;
int j = 0;
printf(" ");
for (i = 1; i < rows; i++)//在最外圈行标上数字,便于查看雷阵
{
printf("%d ", i);
}
printf("\n");
for (i = 1; i < rows; i++)
{
printf("%d ", i);//在最外圈每列标上数字
for (j = 1; j < cols; j++)
{
printf("%c ", show[i][j]);//打印出雷阵页面
}
printf("\n");
}
return 0;
}
测试函数
#include "game.h"
void menu()//打印菜单
{
printf("##############1.开始游戏##############\n");
printf("##############0.退出游戏##############\n");
}
int main()
{
char mine[rows][cols];//雷阵
char show[rows][cols];//显示雷阵
int i = 0;
int j = 0;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
mine[i][j] = '*';
show[i][j] = '0';
}
}//初始化两个数组
int input;
while (input)
{
menu();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
printf("开始游戏");
game(mine, show);
break;
case 0:
printf("退出游戏");
break;
default:
printf("输入错误\n");
break;
}
}
return 0;
}