当前位置:首页 > JavaScript

js实现迷宫

2026-03-13 16:38:56JavaScript

实现迷宫的基本思路

使用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);
            }
        }
    }
}

添加用户交互

允许用户通过键盘或鼠标在迷宫中导航。以下是一个键盘控制的示例:

js实现迷宫

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迷宫,并根据需求扩展功能。

标签: 迷宫js
分享给朋友:

相关文章

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let curr…

js计算器的实现

js计算器的实现

实现基础结构 HTML部分需要创建计算器的基本框架,包含显示区域和按钮。使用<div>容器包裹整个计算器,内部设置一个显示屏和多个按钮。 <div class="calculato…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…

js 实现拖拽

js 实现拖拽

实现拖拽的基本步骤 在JavaScript中实现拖拽功能需要监听几个关键事件:mousedown、mousemove和mouseup。以下是实现的基本逻辑。 监听目标元素的mousedown事件,记…

js实现文件夹

js实现文件夹

使用JavaScript创建文件夹 在浏览器端的JavaScript中无法直接操作文件系统创建文件夹,这是出于安全考虑。但在Node.js环境中可以通过文件系统模块(fs)实现。 Node.js中使…