C++ 控制台扫雷
花了一下午写出来的控制台扫雷,主要通过修改和打印数组来实现。
主要的问题点:
1.在显示地图的过程中,既要显示数字,又要显示雷和符号,所以的用string类型的二维向量,vector<vector<string.>>;中间要利用ASCII码将int型的数字转化为字符串。
2.生成地图的时候,雷是随机的,我这里采用的做法是取余生成雷,举个例子,如果雷数是格子数的十分之一,那我遍历整个二维数组,在rand()%8 == 0时放置一颗雷,当放置10颗之后停止,这样可能会导致我的雷都偏前面一点,哈哈。
3.对于没有雷的格子,需要做一个遍历,统计周边的雷数,为了方便,实际地图要大一圈,实际的边长+2,边不作为地图,只为统计雷数时方便存在。
4.当点开一颗雷之后,如果数字是0,那么四周为0的数字也要被点亮,因此在这里使用递归实现dfs。
5.在每次进行一个格子操作之后,使用一个count计数,所有格子操作完后,游戏结束统计游戏结果,在此之前,踩到雷也会导致游戏结束。
附上游戏截图和代码
主函数
#include<vector>
#include<algorithm>
#include<functional>
#include<iostream>
#include<windows.h>
#include"gameManager.h"
#include"map.h"
using namespace std;
int main() {
GameManager* game = new GameManager();
while (true) {
int diff = game->difficultNumber();//玩家的难度选择参数
Map* m = new Map(diff);
m->initMap();
while (true) {
m->showMap();
int swicth;
cout << "1.踩雷" << endl;
cout << "2.插旗子" << endl;
cout << "3.取消插旗子" << endl;
cin >> swicth;
if (swicth == 1) {
//踩雷;如果踩到雷了返回1,没踩到返回0
if (game->stepOnMine(m)) break;
}
else if (swicth == 2) {
//插旗子
game->flagMine(m);
}
else if (swicth == 3) {
//取消插旗子
game->cancelFalgMine(m);
}
else {
cout << "您的输入有误!" << endl;
}
//判断格子是否被开完,开完了则取胜
if (m->gameOver()) {
cout << "恭喜你获得胜利!" << endl;
m->showMap();
break;
}
}
int over = 0;
cout << "1.回到主菜单" << endl;
cout << "other.退出游戏" << endl;
cin >> over;
if (over == 1) {
system("cls");
continue;
}
else break;
}
system("pause");
return 0;
}
map类
头文件
```cpp
#pragma once
#include<ctime>
#include <vector>
#include<string>
#include <iostream>
using namespace std;
class Map {
public:
Map(int) ;//根据难度构造地图
void initMap() ;//根据难度初始化地图
string aroudMineNum
(const vector<vector<string>>&, const int&, const int&) const ;//判断某个坐标桌边的雷数
void showMap() ;//打印showMapArray数组
int dateUpMap(const int&, const int&) ;//如果返回值为1,继续,返回值为0表示结束