js实现迷宫
实现迷宫的基本思路
使用JavaScript实现迷宫通常涉及生成迷宫结构、渲染迷宫以及处理用户交互。以下是实现迷宫的几个关键步骤:
生成迷宫算法
常用的迷宫生成算法包括深度优先搜索(DFS)、Prim算法和Kruskal算法。以DFS为例,递归回溯法可以生成完美迷宫(无环路)。
function generateMaze(width, height) {
const grid = Array(height).fill().map(() => Array(width).fill(1));
const stack = [];
const startX = 1;
const startY = 1;
grid[startY][startX] = 0;
stack.push([startX, startY]);
while (stack.length > 0) {
const [x, y] = stack.pop();
const directions = [
[2, 0], [-2, 0], [0, 2], [0, -2]
].sort(() => Math.random() - 0.5);
for (const [dx, dy] of directions) {
const nx = x + dx;
const ny = y + dy;
if (nx > 0 && nx < width - 1 && ny > 0 && ny < height - 1 && grid[ny][nx] === 1) {
grid[ny][nx] = 0;
grid[y + dy / 2][x + dx / 2] = 0;
stack.push([nx, ny]);
}
}
}
return grid;
}
渲染迷宫
使用HTML Canvas或DOM元素渲染迷宫。以下是通过Canvas绘制的示例:
function drawMaze(canvas, maze) {
const ctx = canvas.getContext('2d');
const cellSize = 20;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
for (let y = 0; y < maze.length; y++) {
for (let x = 0; x < maze[y].length; x++) {
if (maze[y][x] === 0) {
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
}
}
}
添加用户交互
允许用户通过键盘或鼠标在迷宫中导航。以下是一个键盘控制的示例:

document.addEventListener('keydown', (e) => {
const key = e.key;
let [newX, newY] = [playerX, playerY];
if (key === 'ArrowUp') newY--;
if (key === 'ArrowDown') newY++;
if (key === 'ArrowLeft') newX--;
if (key === 'ArrowRight') newX++;
if (maze[newY][newX] === 0) {
playerX = newX;
playerY = newY;
drawPlayer();
}
});
完整示例代码
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Maze</title>
<style>
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="mazeCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('mazeCanvas');
const maze = generateMaze(20, 20);
let playerX = 1;
let playerY = 1;
drawMaze(canvas, maze);
drawPlayer();
function drawPlayer() {
const ctx = canvas.getContext('2d');
const cellSize = 20;
ctx.fillStyle = 'red';
ctx.fillRect(playerX * cellSize, playerY * cellSize, cellSize, cellSize);
}
document.addEventListener('keydown', (e) => {
const key = e.key;
let [newX, newY] = [playerX, playerY];
if (key === 'ArrowUp') newY--;
if (key === 'ArrowDown') newY++;
if (key === 'ArrowLeft') newX--;
if (key === 'ArrowRight') newX++;
if (maze[newY][newX] === 0) {
drawMaze(canvas, maze);
playerX = newX;
playerY = newY;
drawPlayer();
}
});
</script>
</body>
</html>
扩展功能
- 迷宫求解算法:实现A*或Dijkstra算法自动寻找路径。
- 动态生成:调整迷宫大小或复杂度。
- 可视化效果:添加动画展示迷宫生成或求解过程。
通过以上方法,可以快速实现一个基础的JavaScript迷宫,并根据需求扩展功能。






