用c++代码写一个扫雷小游戏
时间: 2023-12-29 08:23:34 浏览: 135
以下是用C++代码实现扫雷小游戏的基本步骤:
```C++
//定义常量
const int N = 105;
const int M = 105;
const int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
const int dy[8] = {1, -1, 0, 0, 1, -1, 1, -1};
//定义变量
int n, m, k, cnt;
char a[N][M], b[N][M];
bool vis[N][M];
//初始化
void init() {
memset(a, '.', sizeof(a));
memset(b, '0', sizeof(b));
memset(vis, false, sizeof(vis));
cnt = 0;
}
//生成雷区
void build() {
while (cnt < k) {
int x = rand() % n + 1;
int y = rand() % m + 1;
if (a[x][y] == '*') continue;
a[x][y] = '*';
cnt++;
}
}
//计算周围雷数
void calc() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] == '*') continue;
for (int k = 0; k < 8; k++) {
int x = i + dx[k];
int y = j + dy[k];
if (x < 1 || x > n || y < 1 || y > m) continue;
if (a[x][y] == '*') b[i][j]++;
}
}
}
}
//递归展开
void dfs(int x, int y) {
vis[x][y] = true;
if (b[x][y] != '0') return;
for (int i = 0; i < 8; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 1 || nx > n || ny < 1 || ny > m) continue;
if (vis[nx][ny]) continue;
dfs(nx, ny);
}
}
//主函数
int main() {
srand(time(NULL));
cin >> n >> m >> k;
init();
build();
calc();
dfs(1, 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (vis[i][j]) cout << b[i][j];
else cout << ".";
}
cout << endl;
}
return 0;
}
```
阅读全文