一、题目

写一个扫雷小游戏,每次输入一个坐标,若该处是地雷,则游戏失败,若该处不是地雷,则显示周围地雷数量,若扫除全部非地雷区域,则扫雷成功。

二、算法

设置两张地图(二维数组)mine和show,一张用于埋雷,一张用于显示当前的排雷情况。

两张地图的大小都比游戏雷场的ROW和COL加了两行两列,方便计算每个点周围的雷数。

mine的数据类型是int,0表示无雷,1表示有雷。

三、代码

#define _CRT_SECURE_NO_WARNINGS 1#include #include #include using namespace std;#define ROW 5#define COL 5#define ROWS (ROW + 2)#define COLS (COL + 2)#define BOOM 3class Game{public:void Init(){memset(_mine, 0, sizeof(int) * ROWS * COLS);memset(_show, '*', ROWS * COLS);_boom = BOOM;for (int i = 0; i < ROWS; ++i)for (int j = 0; j < COLS; ++j)_mine[i][j] == 0;// 埋雷while (_boom){int x = rand() % ROW + 1;int y = rand() % COL + 1;if (_mine[x][y] != 1){_mine[x][y] = 1;--_boom;}}}void Display(){system("cls");cout << "--------- 扫雷 ---------" << endl << " ";for (int i = 1; i <= COL; ++i)printf("%2d ", i);cout << endl;for (int i = 1; i <= ROW; ++i){printf("%2d ", i);for (int j = 1; j <= COL; ++j){cout << ' ' << _show[i][j] << ' ';}cout << endl;}}void ShowMines(){cout << endl << endl;cout << "--------- 雷场 ---------" << endl << " ";for (int i = 1; i <= COL; ++i)printf("%2d ", i);cout << endl;for (int i = 1; i <= ROW; ++i){printf("%2d ", i);for (int j = 1; j <= COL; ++j){if (_mine[i][j] == 0)cout << " ";elsecout << " B ";}cout << endl;}}char GetMineCount(int x, int y){return _mine[x - 1][y - 1] + _mine[x][y - 1] + _mine[x + 1][y - 1]+ _mine[x - 1][y + 1] + _mine[x][y + 1] + _mine[x + 1][y + 1] + _mine[x - 1][y] + _mine[x + 1][y] + '0';}void Sweep(){int count = ROW * COL - BOOM;while (count){int x, y;cout <> x >> y;if (x < 1 || y  ROW || y > COL){cout << "坐标输入不合法,请重新输入" << endl;continue;}if (_mine[x][y] == 1){ShowMines();cout << endl << "很遗憾, 你踩到地雷了……" << endl;return;}else{_show[x][y] = GetMineCount(x, y);Display();count--;}}cout << endl << "恭喜你,扫雷成功!" << endl;ShowMines();}private:int _mine[ROWS][COLS];char _show[ROWS][COLS];int _boom;};int main(){srand((unsigned int)time(nullptr));Game game;game.Init();game.Display();game.Sweep();return 0;}

四、测试