迷宫绘画与画布

时间:2019-03-12 08:47:51

标签: javascript typescript canvas maze

作为附带项目,我使用图形创建了一个迷宫生成器。生成的逻辑工作正常,但渲染时遇到一些问题。按照我的逻辑,每个单元格都表示为4条边的阵列,其中第一个边是顶墙,第二个边是右墙,依此类推。如果有一条边(不同于-1的边),则应该有一堵墙;如果有-1,那边应该是开放的。

为了尝试遵循此逻辑,我创建了以下Render类

export class Renderer {
  private _context: CanvasRenderingContext2D;
  private _y: number;
  private _x: number;

  constructor(canvas: HTMLCanvasElement, xSize: number, ySize: number) {
    this._context = canvas.getContext('2d') as CanvasRenderingContext2D;
    this._x = xSize;
    this._y = ySize
  }


  public render(graphAdjacencyList: Array<Vertex>): void {
    for (let i = 0; i < this._x; i++) {
      for (let j = 0; j < this._y; j++) {
        const codedIndex: number = parseInt(i.toString() + j.toString());
        this._renderCell({ x: 20 * j, y: 20 * i }, graphAdjacencyList[codedIndex].getEdges(), 20)
      }
    }
  }


  private _renderCell(coords: Record<'x' | 'y', number>, cellWalls: Array<number>, size: number) {
    cellWalls.forEach((w: number, index: number) => {
      this._context.beginPath();
      switch (index) {
        case 0:
          this._context.moveTo(coords.x, coords.y);
          (w !== -1) ? this._context.lineTo(coords.x + size, coords.y) : null;
          break;
        case 1:
          this._context.moveTo(coords.x + size, coords.y);
          (w !== -1) ? this._context.lineTo(coords.x + size, coords.y + size) : null;
          break;
        case 2:
          this._context.moveTo(coords.x + size, coords.y + size);
          (w !== -1) ? this._context.lineTo(coords.x, coords.y + size) : null;
          break;
        case 3:
          this._context.moveTo(coords.x, coords.y + size);
          (w !== -1) ? this._context.lineTo(coords.x, coords.y - size) : this._context.moveTo(coords.x, coords.y - size);
          break;
      }

      this._context.closePath();
      this._context.stroke();
    });
  }
}

乍一看似乎还不错,除了它像该图像5X5 maze

那样渲染“鬼墙”(灰色笔触)的事实

如果我瞥一眼边缘,我会看到例如单元格[3][3]应该只有顶壁和左壁,因为它的边缘是[23, -1, -1, 32]。我坚信错误在于我如何移动要点,但我无法完全确定问题所在。

最小示例:https://stackblitz.com/edit/js-ys9a1j

在最小的示例中,该图不是随机的,而是设计为结果应包含在所有块中,以仅具有底壁和左壁([-1,-1,1,1])

1 个答案:

答案 0 :(得分:0)

我发现了问题,与一位朋友一起检查了代码,我们注意到渲染单元的情况3画错了线。这就是固定代码的方式。

多亏了Kaiido,我甚至用较浅的灰色笔触解决了这个问题,他建议将坐标偏移0.5。

  case 3:
          this._adjustedMoveTo(coords.x, coords.y + size);
          (w !== -1) ? this._adjustedLineTo(coords.x, coords.y) : null
          break;
      }
相关问题