js实现迷宫
JavaScript 实现迷宫
在 JavaScript 中实现迷宫通常涉及迷宫生成算法和可视化。以下是两种常见的迷宫生成方法及其实现代码:

深度优先搜索(DFS)算法
DFS 是一种递归算法,通过随机选择相邻未访问的单元格并打通墙壁来生成迷宫:

class Maze {
constructor(width, height) {
this.width = width;
this.height = height;
this.grid = Array(height).fill().map(() => Array(width).fill(true));
this.visited = Array(height).fill().map(() => Array(width).fill(false));
}
generate(x = 0, y = 0) {
this.visited[y][x] = true;
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]].sort(() => Math.random() - 0.5);
for (const [dx, dy] of directions) {
const nx = x + dx * 2, ny = y + dy * 2;
if (nx >= 0 && nx < this.width && ny >= 0 && ny < this.height && !this.visited[ny][nx]) {
this.grid[y + dy][x + dx] = false;
this.generate(nx, ny);
}
}
}
render() {
let output = '';
for (const row of this.grid) {
output += row.map(cell => cell ? '#' : ' ').join('') + '\n';
}
console.log(output);
}
}
const maze = new Maze(21, 21); // 奇数宽度/高度确保边界正确
maze.generate();
maze.render();
Prim 算法
Prim 算法通过随机选择边界墙并连接未访问的单元格来生成迷宫:
class MazePrim {
constructor(width, height) {
this.width = width;
this.height = height;
this.grid = Array(height).fill().map(() => Array(width).fill(true));
this.frontiers = [];
}
generate(startX = 1, startY = 1) {
this.grid[startY][startX] = false;
this.addFrontiers(startX, startY);
while (this.frontiers.length > 0) {
const [x, y] = this.frontiers.splice(Math.floor(Math.random() * this.frontiers.length), 1)[0];
const neighbors = this.getNeighbors(x, y);
if (neighbors.length > 0) {
const [nx, ny] = neighbors[Math.floor(Math.random() * neighbors.length)];
this.grid[y][x] = false;
this.grid[(y + ny) / 2][(x + nx) / 2] = false;
this.addFrontiers(x, y);
}
}
}
addFrontiers(x, y) {
const directions = [[2, 0], [-2, 0], [0, 2], [0, -2]];
for (const [dx, dy] of directions) {
const nx = x + dx, ny = y + dy;
if (nx > 0 && nx < this.width - 1 && ny > 0 && ny < this.height - 1 && this.grid[ny][nx]) {
this.frontiers.push([nx, ny]);
}
}
}
getNeighbors(x, y) {
const directions = [[2, 0], [-2, 0], [0, 2], [0, -2]];
return directions
.map(([dx, dy]) => [x + dx, y + dy])
.filter(([nx, ny]) => nx >= 0 && nx < this.width && ny >= 0 && ny < this.height && !this.grid[ny][nx]);
}
}
const maze = new MazePrim(21, 21);
maze.generate();
console.log(maze.grid.map(row => row.map(cell => cell ? '#' : ' ').join('')).join('\n'));
可视化实现(HTML/CSS)
将生成的迷宫渲染到网页:
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: monospace; line-height: 1; }
.cell { display: inline-block; width: 10px; height: 10px; }
.wall { background: black; }
.path { background: white; }
</style>
</head>
<body>
<div id="maze"></div>
<script>
class Maze {
constructor(width, height) {
this.width = width;
this.height = height;
this.grid = Array(height).fill().map(() => Array(width).fill(1));
}
generate() {
// 使用DFS或Prim算法生成迷宫
// 示例代码省略(参考前面的实现)
}
render() {
const container = document.getElementById('maze');
container.innerHTML = '';
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
const cell = document.createElement('div');
cell.className = this.grid[y][x] ? 'cell wall' : 'cell path';
container.appendChild(cell);
}
container.appendChild(document.createElement('br'));
}
}
}
const maze = new Maze(21, 21);
maze.generate();
maze.render();
</script>
</body>
</html>
关键注意事项
- 迷宫尺寸应为奇数,确保有完整的边界和通路
- 深度优先搜索生成的迷宫通常有长走廊,而Prim算法生成的迷宫分支更多
- 可通过调整随机选择策略来改变迷宫风格
- 路径查找算法(如A*)可添加到生成的迷宫中






