js实现迷宫游戏
实现迷宫游戏的基本思路
迷宫游戏的核心包括迷宫生成、玩家移动控制和碰撞检测。以下是使用JavaScript实现的基本步骤。
迷宫生成算法
深度优先搜索(DFS)是常用的迷宫生成算法。通过递归或栈实现随机路径生成,确保迷宫有解。
function generateMaze(width, height) {
const grid = Array(height).fill().map(() => Array(width).fill(1));
const stack = [];
const start = { x: 1, y: 1 };
grid[start.y][start.x] = 0;
stack.push(start);
while (stack.length) {
const current = stack.pop();
const neighbors = getUnvisitedNeighbors(current, grid);
if (neighbors.length) {
stack.push(current);
const next = neighbors[Math.floor(Math.random() * neighbors.length)];
grid[next.y][next.x] = 0;
stack.push(next);
}
}
return grid;
}
function getUnvisitedNeighbors(cell, grid) {
const dirs = [[0, 2], [2, 0], [0, -2], [-2, 0]];
return dirs.map(([dx, dy]) => ({ x: cell.x + dx, y: cell.y + dy }))
.filter(next =>
next.x > 0 && next.y > 0 &&
next.x < grid[0].length - 1 &&
next.y < grid.length - 1 &&
grid[next.y][next.x] === 1
);
}
渲染迷宫到Canvas
使用HTML Canvas绘制迷宫,1表示墙,0表示通路。
function drawMaze(ctx, maze, cellSize) {
ctx.fillStyle = 'black';
for (let y = 0; y < maze.length; y++) {
for (let x = 0; x < maze[y].length; x++) {
if (maze[y][x] === 1) {
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
}
}
}
玩家控制与移动
监听键盘事件控制玩家移动,并检测是否碰撞墙壁。
const player = { x: 1, y: 1, size: 10 };
document.addEventListener('keydown', (e) => {
const prevPos = { ...player };
if (e.key === 'ArrowUp') player.y--;
if (e.key === 'ArrowDown') player.y++;
if (e.key === 'ArrowLeft') player.x--;
if (e.key === 'ArrowRight') player.x++;
// 碰撞检测
if (maze[player.y][player.x] === 1) {
Object.assign(player, prevPos);
}
redraw();
});
完整示例代码
整合生成、渲染和控制逻辑的完整示例:
<!DOCTYPE html>
<html>
<body>
<canvas id="mazeCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('mazeCanvas');
const ctx = canvas.getContext('2d');
const cellSize = 20;
const maze = generateMaze(20, 20);
const player = { x: 1, y: 1, size: cellSize / 2 };
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawMaze(ctx, maze, cellSize);
ctx.fillStyle = 'red';
ctx.fillRect(
player.x * cellSize + (cellSize - player.size) / 2,
player.y * cellSize + (cellSize - player.size) / 2,
player.size,
player.size
);
}
document.addEventListener('keydown', (e) => {
const prevPos = { ...player };
if (e.key === 'ArrowUp') player.y--;
if (e.key === 'ArrowDown') player.y++;
if (e.key === 'ArrowLeft') player.x--;
if (e.key === 'ArrowRight') player.x++;
if (maze[player.y][player.x] === 1) {
Object.assign(player, prevPos);
}
redraw();
});
redraw();
</script>
</body>
</html>
扩展功能建议
- 终点检测:设置终点坐标,当玩家到达时触发胜利条件。
- 动画效果:使用
requestAnimationFrame平滑移动。 - 难度调整:通过修改迷宫尺寸或算法复杂度调整难度。
通过以上步骤,可以实现一个基础的迷宫游戏,并根据需求进一步扩展功能。







