本文将介绍如何用100行C语言代码实现扫雷小游戏的基本功能。
游戏画面:
源码:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define N 11
#define M 11
main()
{
int i=0,j=0,p=0; //i、j、p为循环参数
int x=0,y=0; //x和y为地图坐标参数
int end1=0,end2=0; //end1为地图中不是雷的位置数目,end2为判断是否踩雷的参数
int t=0; //用作赋值的中间变量
char ch;
static int minemap[N][M];
char showmap[N][M]={" 123456789",
"1*********",
"2*********",
"3*********",
"4*********",
"5*********",
"6*********",
"7*********",
"8*********",
"9*********"};
for(i=1;i<10;i++)
{
for(j=1;j<10;j++)
{
minemap[i][j]=rand()%90;
if(minemap[i][j]/10>0)
{
minemap[i][j]=0;
end1++; //用end1的数目表示所绘制minemap中不是雷的位置的个数
}
else
{
minemap[i][j]=1;
}
}
}
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%c ",showmap[i][j]);
}
printf("\n");
}
for(p=0;p<end1;p++) //当用户点击地图的次数=end1时代表所有非雷的地点都被点过了,跳出循环,游戏胜利
{
reinput:printf("Please input the chosen coordinate x,y:\n");
while(scanf("%d%d",&x,&y)!=2)
{
printf("The input are not allowed!\n");
ch=getchar();
goto reinput;
}
switch(x>0&&x<10)
{
case 0:
{
printf("The input are not allowed!\n");
goto reinput;
}
default:break;
}
switch(y>0&&y<10)
{
case 0:
{
printf("The input are not allowed!\n");
goto reinput;
}
default:break;
}
if(minemap[x][y]==1)
{
printf("This is a mine, you died.\n");
end2=1;
break;
}
else
{
t=minemap[x-1][y-1]+minemap[x-1][y]+minemap[x-1][y+1]+minemap[x][y-1]+minemap[x][y+1]+minemap[x+1][y-1]+minemap[x+1][y]+minemap[x+1][y+1];
showmap[x][y]=t+48; //48在Ascii码中代表字符0
}
system("cls");
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%c ",showmap[i][j]);
}
printf("\n");
}
}
if(end2==1)
{
printf("game over\n");
}
else
{
printf("Winner! You are amazing!\n");
}
}
功能实现思路:
1、建立两个数组,一个int型数组保存地雷,另一个char型保存用户看到的地图。
2、生成地雷,用rand()给int型数组赋值,随机数产生范围为0~89, 凡是产生的随机数在0~9内的就是雷。
3、打印用户看到的char型数组。
4、用户点击地图的次数=end1时代表所有非雷的地点都被点过了,跳出循环,游戏胜利。
5、这段代码用scanf的返回值保证输入的是数字,用switch语句保证输入的范围在1~9内。ch=getchar()用以吃掉因为输入字符产生的回车字符‘\n’。
6、如果是值为1则说明踩雷,并且将end2置为1,这样退出循环后就可以根据end2的值判断是因为踩雷退出的还是正常退出的。
7、用于统计周边8个点位的1的个数,并且将数值转换为字符并保存在char型数组中,准备展示给玩家。
8、清屏后重新打印char型数组。
9、退出循环后根据end2的值判断结果。