当前位置:首页 > JavaScript

js实现迷宫

2026-01-31 18:45:27JavaScript

JavaScript 实现迷宫

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

深度优先搜索(DFS)算法

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

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)

将生成的迷宫渲染到网页:

js实现迷宫

<!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
分享给朋友:

相关文章

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Java…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

利用js实现

利用js实现

使用 JavaScript 实现 在 JavaScript 中,可以通过多种方式实现功能,具体取决于需求。以下是几种常见的方法: 方法一:使用原生 JavaScript // 示例代码…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…