使用C++制作一个迷宫生成器
时间: 2024-05-10 17:19:31 浏览: 11
好的,下面是一个简单的迷宫生成器示例代码。这个实现使用了深度优先搜索算法(DFS)。
```cpp
#include <iostream>
#include <vector>
#include <stack>
#include <random>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 10;
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
};
struct Cell {
bool visited;
bool walls[4] = { true, true, true, true }; // up, down, left, right
};
vector<Cell> maze(WIDTH * HEIGHT);
int getIndex(int x, int y) {
if (x < 0 || y < 0 || x >= WIDTH || y >= HEIGHT) {
return -1;
}
return x + y * WIDTH;
}
void removeWall(int curr, int next) {
int x = curr % WIDTH - next % WIDTH;
if (x == -1) {
maze[curr].walls[(int)Direction::RIGHT] = false;
maze[next].walls[(int)Direction::LEFT] = false;
} else if (x == 1) {
maze[curr].walls[(int)Direction::LEFT] = false;
maze[next].walls[(int)Direction::RIGHT] = false;
}
int y = curr / WIDTH - next / WIDTH;
if (y == -1) {
maze[curr].walls[(int)Direction::DOWN] = false;
maze[next].walls[(int)Direction::UP] = false;
} else if (y == 1) {
maze[curr].walls[(int)Direction::UP] = false;
maze[next].walls[(int)Direction::DOWN] = false;
}
}
void createMaze(int start) {
stack<int> s;
s.push(start);
maze[start].visited = true;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dis(0, 3);
while (!s.empty()) {
int curr = s.top();
s.pop();
int neighbors[4] = { getIndex(curr % WIDTH, curr / WIDTH - 1), // up
getIndex(curr % WIDTH, curr / WIDTH + 1), // down
getIndex(curr % WIDTH - 1, curr / WIDTH), // left
getIndex(curr % WIDTH + 1, curr / WIDTH) // right
};
vector<int> unvisitedNeighbors;
for (int i = 0; i < 4; i++) {
if (neighbors[i] != -1 && !maze[neighbors[i]].visited) {
unvisitedNeighbors.push_back(neighbors[i]);
}
}
if (!unvisitedNeighbors.empty()) {
s.push(curr);
int nextIndex = unvisitedNeighbors[dis(gen) % unvisitedNeighbors.size()];
removeWall(curr, nextIndex);
maze[nextIndex].visited = true;
s.push(nextIndex);
}
}
}
void printMaze() {
cout << " ";
for (int i = 0; i < WIDTH; i++) {
cout << "__";
}
cout << endl;
for (int y = 0; y < HEIGHT; y++) {
cout << "|";
for (int x = 0; x < WIDTH; x++) {
int index = getIndex(x, y);
if (maze[index].walls[(int)Direction::DOWN]) {
cout << "_";
} else {
cout << " ";
}
if (maze[index].walls[(int)Direction::RIGHT]) {
cout << "|";
} else {
cout << " ";
}
}
cout << endl;
}
}
int main() {
createMaze(getIndex(0, 0));
printMaze();
return 0;
}
```
这个代码使用了一个 `Cell` 结构体来表示每个迷宫单元格。每个单元格有四堵墙(上、下、左、右),并且它们会被标记为已访问或未访问。在 `createMaze` 函数中,我们使用深度优先搜索算法来遍历所有的单元格,并且随机选择一个未访问的邻居单元格来与当前单元格连接。这个过程会一直重复,直到所有单元格都被访问过。
在 `removeWall` 函数中,我们会移除当前单元格和下一个单元格之间的墙,以此来连接它们。最后,`printMaze` 函数会输出生成的迷宫。