js随机绘制迷宫及离开迷宫路线最优解代码

代码语言:html

所属分类:其他

代码描述:js随机绘制迷宫及离开迷宫路线最优解代码

代码标签: js 随机 绘制 迷宫 离开 迷宫 路线 最优解 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
  
<style>
html {
  background-color: #eee;
  font-family: sans-serif;
}
h1 {
  text-align: center;
}
canvas {
  border: 1px solid #000;
  display: block;
  margin: 0 auto;
  background: #f0f0f0;
}
#controls {
  text-align: center;
  margin-top: 20px;
}
</style>

  
</head>

<body translate="no">
  <h1>Random Maze</h1>
<canvas id="mazeCanvas" width="600" height="600"></canvas>
<div id="controls">
  <input type="checkbox" id="showSolution" />
  <label for="showSolution">Show Solution</label>
</div>
  
      <script  >
const canvas = document.getElementById("mazeCanvas");
const ctx = canvas.getContext("2d");

const cols = 25;
const rows = 25;
const cellSize = canvas.width / cols;

let grid = [];
let stack = [];
let solutionPath = [];

class Cell {
  constructor(i, j) {
    this.i = i;
    this.j = j;
    this.walls = [true, true, true, true]; // top, right, bottom, left
    this.visited = false;
  }

  draw() {
    const x = this.i * cellSize;
    const y = this.j * cellSize;

    ctx.strokeStyle = "#000";
    ctx.lineWidth = 2;

    if (this.walls[0]) {
      ctx.beginPath();
      ctx.moveTo(x, y);
      ctx.lineTo(x + cellSize, y);
      ctx.stroke();
    }
    if (this.walls[1]) {
      ctx.beginPath();
      ctx.moveTo(x + cellSize, y);
      ctx.lineTo(x + cellSize, y + cellSize);
      ctx.stroke();
    }
    if (this.walls[2]) {
      ctx.beginPath();
      ctx.moveTo(x + cellSize, y + cellSize);
      ctx.lineTo(x, y + cellSize);
      ctx.stroke();
    }
    if (this.walls[3]) {
      ctx.beginPath();
      ctx.moveTo(x, y + cellSize);
      ctx.lineTo(x, y);
      ctx.stroke();
    }

    if (this.visited) {
      ctx.fillStyle = "#fff";
      ctx.fillRect(x, y, cellSize, cellSize);
    }
  }

  highlight(col.........完整代码请登录后点击上方下载按钮下载查看

网友评论0