I recently developed a maze generator as a personal project utilizing a graph. While the generation logic works perfectly, I am facing challenges when it comes to rendering the maze. In my approach, each cell is represented by an array of 4 edges where the first edge corresponds to the top wall, the second one to the right wall, and so forth in a clockwise direction. If there is a value other than -1 in an edge, it indicates the presence of a wall; if the value is -1, that side should remain open.
To align with this logic, I constructed the following Render class:
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();
});
}
}
Initially, this renderer seems to work fine, except for the occurrence of "ghost walls" (light grey strokes) as displayed in this image https://i.stack.imgur.com/fL0AV.png
Upon inspecting the edges, I observed that, for instance, the cell at position [3][3]
should only have the top and left walls due to its edges being [23, -1, -1, 32]
. I suspect the issue lies in how I handle point movements, but I haven't been able to identify the exact problem.
For a minimal demonstration, you can refer to this example: https://stackblitz.com/edit/js-ys9a1j
In the provided example, although the graph isn't randomized, the result should ideally feature all blocks with only bottom and left walls ([-1,-1, 1, 1]).