js实现迷宫游戏
实现迷宫游戏的基本思路
使用JavaScript实现迷宫游戏需要处理迷宫生成、角色移动、碰撞检测和胜利条件等核心逻辑。通常结合HTML5的Canvas或DOM操作来渲染游戏界面。
迷宫生成算法
深度优先搜索(DFS)算法适合生成迷宫:
function generateMaze(width, height) {
const maze = Array(height).fill().map(() => Array(width).fill(1));
const stack = [];
const start = {x: 1, y: 1};
maze[start.y][start.x] = 0;
stack.push(start);
while (stack.length) {
const current = stack.pop();
const directions = [
{dx: 2, dy: 0}, {dx: -2, dy: 0},
{dx: 0, dy: 2}, {dx: 0, dy: -2}
].sort(() => Math.random() - 0.5);
for (const dir of directions) {
const nx = current.x + dir.dx;
const ny = current.y + dir.dy;
if (nx > 0 && nx < width-1 && ny > 0 && ny < height-1 && maze[ny][nx] === 1) {
maze[ny][nx] = 0;
maze[current.y + dir.dy/2][current.x + dir.dx/2] = 0;
stack.push({x: nx, y: ny});
}
}
}
return maze;
}
游戏渲染与交互
使用Canvas绘制迷宫和玩家:
const canvas = document.getElementById('maze');
const ctx = canvas.getContext('2d');
const cellSize = 20;
let player = {x: 1, y: 1};
const maze = generateMaze(21, 21); // 奇数尺寸确保有解
function drawMaze() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制墙壁
maze.forEach((row, y) => {
row.forEach((cell, x) => {
if (cell === 1) {
ctx.fillStyle = '#333';
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
});
});
// 绘制玩家
ctx.fillStyle = 'red';
ctx.fillRect(
player.x * cellSize + 2,
player.y * cellSize + 2,
cellSize - 4,
cellSize - 4
);
// 绘制终点
ctx.fillStyle = 'green';
ctx.fillRect(
(maze[0].length-2) * cellSize + 2,
(maze.length-2) * cellSize + 2,
cellSize - 4,
cellSize - 4
);
}
玩家移动控制
监听键盘事件处理移动:
document.addEventListener('keydown', (e) => {
const moves = {
ArrowUp: {dx: 0, dy: -1},
ArrowDown: {dx: 0, dy: 1},
ArrowLeft: {dx: -1, dy: 0},
ArrowRight: {dx: 1, dy: 0}
};
if (moves[e.key]) {
const newX = player.x + moves[e.key].dx;
const newY = player.y + moves[e.key].dy;
if (maze[newY][newX] === 0) {
player.x = newX;
player.y = newY;
drawMaze();
checkWin();
}
}
});
胜利条件检测
当玩家到达迷宫右下角时判定胜利:
function checkWin() {
if (player.x === maze[0].length-2 && player.y === maze.length-2) {
setTimeout(() => alert('恭喜通关!'), 100);
}
}
完整游戏初始化
启动游戏的主函数:
function initGame() {
canvas.width = maze[0].length * cellSize;
canvas.height = maze.length * cellSize;
drawMaze();
}
initGame();
扩展功能建议
增加计时功能提升游戏性:
let startTime = Date.now();
function checkWin() {
if (player.x === maze[0].length-2 && player.y === maze.length-2) {
const timeTaken = (Date.now() - startTime) / 1000;
setTimeout(() => alert(`通关时间: ${timeTaken.toFixed(2)}秒`), 100);
}
}
添加难度选择控制迷宫大小:
function setDifficulty(size) {
maze = generateMaze(size, size);
player = {x: 1, y: 1};
initGame();
}
这个实现提供了迷宫游戏的核心机制,可根据需要进一步扩展如添加动画效果、音效或更复杂的迷宫生成算法。







