c++小练习——简易版扫雷游戏,代码如下:
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
void menu();
void game();
void initialize_mineboard(char mine[][11], char set);
void print_mineboard(char mine[][11]);
void set_laymine(char lay_mine[][11]);
void set_searchmine(char lay_mine[][11],char search_mine[][11]);
int mine_message(char lay_mine[][11], int i, int j);
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
cout << "请选择: ";
cin >> input;
switch (input)
{
case 1:
cout << "开始游戏" << endl;
game();
break;
case 0:
cout << "退出游戏" << endl;
break;
default:
cout << "选择错误。请重新选择" << endl;
break;
}
} while (input);
return 0;
}
void game()
{
char lay_mine[11][11];//存放布雷信息
char search_mine[11][11];//存放排查出雷的信息
initialize_mineboard(lay_mine,'0');//初始化布雷数组
initialize_mineboard(search_mine,'*');//初始化排雷数组
print_mineboard(search_mine);//打印初始化棋盘
set_laymine(lay_mine);//布雷
set_searchmine(lay_mine,search_mine);//排雷
}
void menu()
{
cout << "**********************" << endl;
cout << "****** 扫雷游戏 ******" << endl;
cout << "******* 1.play *******" << endl;
cout << "******* 0.exit *******" << endl;
cout << "**********************" << endl;
}
void initialize_mineboard(char mine[][11],char set)//初始化存放数组
{
int i = 0;
int j = 0;
for (i = 0;i < 11;i++)
for (j = 0;j < 11;j++)
mine[i][j] = set;
}
void print_mineboard(char mine[][11])//打印数组
{
int i = 0;
int j = 0;
for (i = 1;i <= 9;i++)
{
for (j = 1;j <=9;j++)
cout << "----";
cout << endl;
for (j = 1;j <=9;j++)
cout <<' '<< mine[i][j] << " |";
cout << endl;
}
for (j = 1;j <=9;j++)
cout << "----";
cout << endl;
}
void set_laymine(char lay_mine[][11])//布雷
{
int n = 10;//布置10个雷
while (n)
{
int i = rand() % 9 + 1;//随机布雷
int j = rand() % 9 + 1;
if (lay_mine[i][j] == '0')
{
lay_mine[i][j] = '1';//雷的标志设为‘1’,没有雷的标志设为‘0’;
n--;
}
}
}
void set_searchmine(char lay_mine[][11],char search_mine[][11])//排雷
{
int i = 0;
int j = 0;
int flag =0;
while(flag<71)
{
cout << "请输入要排查的坐标:" << endl;
cin >> i >> j;
if ((i >= 1 && i <= 9) && (j >= 1 && j <= 9))
{
if (lay_mine[i][j] == '1')
{
cout<<"很遗憾,你所输入坐标为雷区,游戏失败!"<<endl;
print_mineboard(lay_mine);
break;
}
else
{
search_mine[i][j] = mine_message(lay_mine, i, j) + '0';
flag++;
print_mineboard(search_mine);
}
}
else
cout<<"输入坐标不合法,请重新输入"<<endl;
}
if (flag == 71)
{
cout << "恭喜你,排雷成功!" << endl;
print_mineboard(lay_mine);
}
}
int mine_message(char lay_mine[][11], int i,int j)//所输入坐标周围雷的个数
{
int x = i - 1;
int y = j - 1;
int count = 0;
for (x = i - 1;x <= i + 1;i++)
for (x = i - 1;y <= j + 1;j++)
if (lay_mine[x][y] == '1')
count++;
return count;
}
|