当前位置:首页 > JavaScript

js实现迷宫

2026-01-31 18:45:27JavaScript

JavaScript 实现迷宫

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

js实现迷宫

深度优先搜索(DFS)算法

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

js实现迷宫

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*)可添加到生成的迷宫中

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

相关文章

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval 实…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个回…