You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Canvas迷宫生成器入口标记位置不符问题求助

迷宫生成器入口标记修复方案

问题分析

你的代码存在两个核心问题导致入口标记显示异常:

  • 绿色入口标记固定绘制在房间中心,没有匹配对应的入口方向
  • 东(E)方向的入口绘制坐标错误,导致入口被画到房间外部区域

修复后的代码

JavaScript 代码

const canvas = document.getElementById('Canvas');
const dimensions = {
  width: canvas.width,
  height: canvas.height
};
const context = canvas.getContext('2d');
const open = ['N', 'E', 'S', 'W'];
let rooms = 0;

class Room {
  constructor(x, y, entrance) {
    this.x = x;
    this.y = y;
    this.entrance = entrance;
    this.exit = open[Math.floor(Math.random() * open.length)];
    while (this.exit === this.entrance) {
      this.exit = open[Math.floor(Math.random() * open.length)];
    }
    context.fillStyle = 'black';
    drawRoom(this.x, this.y, this.entrance, this.exit);
    rooms += 1;
    if (rooms < 10) {
      newRoom(this.x, this.y, this.exit);
    }
  }
}

function drawRoom(x, y, entrance, exit) {
  const size = dimensions.width / 10;
  const centerX = (x * size) + size / 2;
  const centerY = (y * size) + size / 2;

  // 绘制黑色房间主体
  context.fillRect(x * size, y * size, size, size);

  // 根据入口方向绘制绿色标记
  context.fillStyle = 'green';
  const markerSize = 3; // 增大标记让它更明显
  switch (entrance) {
    case 'N':
      // 北入口:房间顶部中间
      context.fillRect(centerX - markerSize/2, y * size, markerSize, markerSize);
      // 绘制北入口通道
      context.fillRect(x * size, y * size, size, size / 10);
      break;
    case 'E':
      // 东入口:房间右侧中间
      context.fillRect(x * size + size - markerSize, centerY - markerSize/2, markerSize, markerSize);
      // 修正东入口通道的y坐标
      context.fillRect(x * size + size - size/10, y * size, size / 10, size);
      break;
    case 'S':
      // 南入口:房间底部中间
      context.fillRect(centerX - markerSize/2, y * size + size - markerSize, markerSize, markerSize);
      // 绘制南入口通道
      context.fillRect(x * size, y * size + size - size/10, size, size / 10);
      break;
    case 'W':
      // 西入口:房间左侧中间
      context.fillRect(x * size, centerY - markerSize/2, markerSize, markerSize);
      // 绘制西入口通道
      context.fillRect(x * size, y * size, size / 10, size);
      break;
  }
}

function newRoom(x, y, exit) {
  switch (exit) {
    case 'N':
      return new Room(x, y + 1, 'S');
    case 'E':
      return new Room(x + 1, y, 'W');
    case 'S':
      return new Room(x, y - 1, 'N');
    case 'W':
      return new Room(x - 1, y, 'E');
  }
}

newRoom(0, 0, 'N');

HTML 代码

<canvas id='Canvas' width='500' height='500'></canvas>

关键修改说明

  • 修正房间坐标计算:原来的centerX和centerY计算逻辑有误,改为直接基于size的倍数计算,更简洁准确
  • 入口标记位置适配:根据每个入口方向,将绿色标记绘制在对应入口的中间位置,比如北入口在房间顶部中间,东入口在房间右侧中间
  • 修复东入口绘制错误:将东入口通道的y起始坐标从错误的位置改为y * size,确保通道画在房间内部
  • 增大标记尺寸:把1x1的标记改成3x3,更容易观察
  • 代码规范优化:类名改为首字母大写的Room,变量名修正为正确的dimensions,使用===替代==提升严谨性

内容的提问来源于stack exchange,提问作者Troy Gomme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:57:12