c加加代码编一个迷宫
时间: 2023-07-24 22:09:55 浏览: 81
好的,以下是一个简单的迷宫生成器的 C++ 代码示例:
```c++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 10;
class Maze {
public:
Maze(int w, int h) : width(w), height(h) {
map.resize(height);
for (int i = 0; i < height; i++) {
map[i].resize(width);
for (int j = 0; j < width; j++) {
if (i == 0 || j == 0 || i == height - 1 || j == width - 1) {
map[i][j] = 1;
} else {
map[i][j] = 0;
}
}
}
}
void generate() {
srand(time(0));
int x = rand() % (width - 2) + 1;
int y = rand() % (height - 2) + 1;
map[y][x] = 2;
generate(x, y);
}
void print() {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
cout << (map[i][j] == 1 ? "#" : (map[i][j] == 2 ? "S" : " "));
}
cout << endl;
}
}
private:
void generate(int x, int y) {
int dirs[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int order[4] = {0, 1, 2, 3};
for (int i = 0; i < 4; i++) {
int r = rand() % 4;
int tmp = order[i];
order[i] = order[r];
order[r] = tmp;
}
for (int i = 0; i < 4; i++) {
int dx = dirs[order[i]][0];
int dy = dirs[order[i]][1];
if (x + dx >= 1 && x + dx < width - 1 && y + dy >= 1 && y + dy < height - 1) {
if (map[y + dy][x + dx] == 0) {
map[y + dy][x + dx] = 1;
generate(x + dx, y + dy);
}
}
}
}
vector<vector<int>> map;
int width, height;
};
int main() {
Maze maze(WIDTH, HEIGHT);
maze.generate();
maze.print();
return 0;
}
```
这个迷宫生成器使用了深度优先搜索算法来生成迷宫,首先将整个地图边缘设置为墙壁,然后随机选择一个起始点(在地图边缘之内),将其标记为起点,并从该点开始生成迷宫。生成过程中,随机选择一个方向(上、下、左、右),前进一步,如果前进的位置是墙壁,则打通两个墙壁之间的通道,并从新的位置开始递归生成迷宫。最终生成的迷宫将起点标记为"S",墙壁标记为"#",空地标记为" "。
阅读全文