菜单

准备写一个基于C的扫雷游戏,这是第一篇,内容:扫雷的主菜单

思路

显示菜单->用户选择->判断用户选项

实现

显示菜单

首先在main函数内显示菜单,菜单显示部分实现在 MainMenu 函数内

int main(void)
{
	while (true)
	{
	int iChoose = -1;
	MainMenu();//加载菜单
	}
}

菜单实现

菜单提供给用户三个选项:

1、开始游戏

2、游戏帮助

3、退出

此处,设定用户选择 1 是开始游戏,用户选择 2 是游戏帮助,用户选择 0 是退出游戏,具体实现如下:

用户选择

显示完菜单之后喊用户输入选项,并将用户的选择保存在 iChoose 中,方便后续进行判断

int main(void)
{
	while (true)
	{
 ...
	printf("please input your choose:");//请输入你的选择
	scanf("%d", &iChoose);//获取iChoose
	}
}

判断用户的选择

在实现菜单时,设置用户选择 0 时退出游戏,用户选择 1 开始游戏,用户选择 2 游戏帮助,其他选项则无效,故而按照此思路进行判断

用户选择 0

此时退出游戏

int main(void)
{
	while (true)
	{
 ...
	//退出
	if (0 == iChoose)
	{
	printf("\n\nExiting the game, please wait!\n");//正在退出游戏,请稍等
	Sleep(100);
	break;
	}
	}
}

用户选择 2

此时显示游戏帮助,由于在 iChoose 为 0 分支内,采用了 break 语句跳出循环,故在此分支内依旧用 if 判断,而不采用 else if 判断

int main(void)
{
	while (true)
	{
 ...
	//帮助
	if (2 == iChoose)
	{
	printf("\n\nThe game has primary, intermediate, advanced and custom modes\n");
	printf("A certain number of mines are randomly arranged in the minefield\n");
	printf("The player needs to find all the blocks that are not mines as soon as possible, but do not step on the mines.\n\n\n");
	Sleep(2000);
	continue;
	}
	}
}

用户选择其他选项

此时为无效输入,由于在 iChoose 为 2 分支内,采用了 continue 语句来结束此次循环,进入下一次循环,故在此分支内依旧用 if 判断,而不采用 else if 判断

int main(void)
{
	while (true)
	{
 ...
	//无效输入
	if (iChoose > 2)
	{
	printf("\n\nInvalid input\n\n");//输入无效
	Sleep(500);
	continue;
	}
	}
}

用户选择 1

此时开始游戏,以上分支均未跑到的话,那用户就是选择 1 了,此处无需判断,直接实现

此处将游戏部分封装在了 Play 函数内,直接调用,调用结束后代表游戏结束,随即询问用户是否再来一局:

如若不来,则退出循环,再在外层循环判断一下,进而退出外层循环

如若需要再来一局,则继续循环,调用 Play 函数,进行游戏

int main(void)
{
 ...
	int iiChoose;
	//游戏
	while (true)
	{
	//PlayMenu();//无等级选择,故无此函数
	Play();
	printf("Do you want another game? 1 Yes, other no");//是否再来一局,1是,其他否
	scanf("%d", &iiChoose);
	if (1 != iiChoose)
	break;
	}
	if (1 != iiChoose)
	break;
	}
}

完整代码

见网盘

扫雷 https://www.alipan.com/s/yVJb2bBk1yj 提取码: 33jm 点击链接保存,或者复制本段内容,打开「阿里云盘」APP ,无需下载极速在线查看,视频原画倍速播放。

作者:EricsT原文地址:https://www.cnblogs.com/EricsT/p/18653190

%s 个评论

要回复文章请先登录注册