用c加加写个扫雷小游戏
时间: 2023-05-13 14:05:13 浏览: 126
好的,以下是一个简单的扫雷小游戏的 C++ 代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAXN = 100;
const int MAXM = 100;
int n, m;
char mine[MAXN][MAXM]; // 存储地图信息
bool vis[MAXN][MAXM]; // 标记是否已经翻开
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}; // 方向数组
int dy[] = {1, -1, 0, 0, 1, -1, -1, 1};
void init() {
// 初始化地图
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mine[i][j] = '0';
vis[i][j] = false;
}
}
// 随机生成地雷
int cnt = n * m / 10;
while (cnt--) {
int x = rand() % n;
int y = rand() % m;
mine[x][y] = '*';
}
}
void print() {
// 打印地图
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (vis[i][j]) {
cout << mine[i][j] << " ";
} else {
cout << "- ";
}
}
cout << endl;
}
}
void dfs(int x, int y) {
// 深度优先搜索
vis[x][y] = true;
if (mine[x][y] == '*') {
// 踩到地雷,游戏结束
cout << "Game Over!" << endl;
print();
exit(0);
}
if (mine[x][y] == '0') {
// 如果周围没有地雷,继续搜索
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny]) {
dfs(nx, ny);
}
}
}
}
int main() {
srand(time(NULL));
cout << "请输入地图大小(n m):";
cin >> n >> m;
init();
while (true) {
print();
int x, y;
cout << "请输入要翻开的格子坐标(x y):";
cin >> x >> y;
if (x < 0 || x >= n || y < 0 || y >= m) {
cout << "坐标不合法,请重新输入!" << endl;
continue;
}
if (vis[x][y]) {
cout << "这个格子已经翻开了,请重新输入!" << endl;
continue;
}
dfs(x, y);
bool win = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mine[i][j] != '*' && !vis[i][j]) {
win = false;
break;
}
}
if (!win) break;
}
if (win) {
cout << "You Win!" << endl;
print();
break;
}
}
return 0;
}
阅读全文