控制台扫雷小游戏
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<Windows.h>
using namespace std;
#define COL 20 /* 定义列数 */
#define ROW 20 /* 定义行数 */
#define BOMB 30 /* 定义炸弹数 */
int map[ROW][COL];
void Print();
void Mine()
{
srand(time(nullptr));
//埋雷
for (int i = 1; i <= BOMB; )
{
int row = rand() % 18 + 1;
int col = rand() % 18 + 1;
if (0 == map[row][col])
{
map[row][col] = 9;
i++;
}
}
//摸类,看周围有多少雷
for (int i = 1; i < ROW-1; i++)
{
for (int j = 1; j < COL-1; j++)
{
if (9 == map[i][j])
{
for (int k = i - 1; k <= i + 1; k++)
for (int l = j - 1; l <= j + 1; l++)
{
if (9 != map[k][l])
map[k][l]++;
}
}
}
}
for (int i = 1; i < ROW - 1; i++)//加密
{
for (int j = 1; j < COL - 1; j++)
{
map[i][j] += 10;
}
}
}
void Trave(int i,int j)
{
map[i][j] -= 10;
if (i<1 || i>ROW - 1 || j<1 || j>COL - 1)//递归出口
return;
for (int x = i-1;x <= i+1;x++)
{
for (int y = j - 1;y <= j + 1; y++)
{
if (19 == map[x][y])//如果是雷,那么可以结束函数了
{
break;
}
else if (10 < map[x][y] && 19 > map[x][y])
{
map[x][y] -= 10;
}
else if(10 == map[x][y])
{
Trave(x, y);
}
}//
}
system("cls");
Print();//建议不要屏蔽,因为看着爽
}
void Print()
{
cout << " 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18" << endl;
cout << endl;
for (int i = 1; i < ROW - 1; i++)
{
cout << " " << i << " ";
for (int j = 1; j < COL - 1; j++)
{
switch (map[i][j])
{
case 1:cout << "①" << " "; break;
case 2:cout << "②" << " "; break;
case 3:cout << "③" << " "; break;
case 4:cout << "④" << " "; break;
case 5:cout << "⑤" << " "; break;
case 6:cout << "⑥" << " "; break;
case 7:cout << "⑦" << " "; break;
case 8:cout << "⑧" << " "; break;
case 9:cout << "※" << " "; break;
default:
cout << "■" << " ";
}
}
cout << endl;
}
}
void GameOver()
{
system("cls");
cout << " ***************************************************************\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * 你踩雷了,你输了! *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " * *\n";
cout << " ***************************************************************\n";
}
bool logic(int x, int y)//核心逻辑
{
if (19 == map[x][y])//如果踩雷
{
map[x][y] -= 10;
Sleep(50);
Print();
GameOver();
return false;
}
else if (10 < map[x][y] && 19 > map[x][y])
{
map[x][y] -= 10;//
Print();
}
else if (10 == map[x][y])
{
Trave(x, y);
}
return true;
}
void Game()
{
Mine();
Print();
int pos_x, pos_y;
while (true)
{
system("cls");
Print();
printf("输入坐标:");
cin >> pos_x >> pos_y;
while ((pos_x < 1 && pos_x > ROW - 1) && (pos_y < 1 && pos_y > COL-1))
{
printf("输入坐标:");
cin >> pos_x >> pos_y;
}
if (!logic(pos_x, pos_y))
{
char y;
bool flag = false;
printf("是否再玩一把Y/N: ");
cin >> y;
switch (y)
{
case 'Y':
case 'y':
Mine();
break;
case 'N':
case 'n':
flag = true;
break;
}
if (flag)
break;
}
}
}
int main(void)
{
Game();
return 0;
}
效果