@ludw1gj/maze-generation
Version:
Maze generation algorithms.
90 lines • 3.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const direction_1 = require("./direction");
const grid_1 = require("./grid");
class Maze {
constructor(height, width) {
this.height = height;
this.width = width;
}
setNewDimensions(height, width) {
this.height = height;
this.width = width;
}
/** Run a recursive backtracking algorithm. */
recursiveBacktracking() {
this.grid = new grid_1.Grid(this.height, this.width);
const stack = [];
const randY = Math.floor(Math.random() * this.grid.height);
const randX = Math.floor(Math.random() * this.grid.width);
const initialPosition = { x: randX, y: randY };
const initialCell = this.grid.getCell(initialPosition);
if (!initialCell) {
throw new Error("invalid initial cell");
}
let currentCell = initialCell;
while (true) {
if (!currentCell.isVisited) {
currentCell.setVisited();
}
const neighbours = this.grid.getUnvisitedNeighbours(currentCell);
if (neighbours.length === 0) {
const poppedCell = stack.pop();
if (!poppedCell) {
return;
}
currentCell = poppedCell;
continue;
}
const { neighbourCell, dir } = grid_1.Grid.getRandomElement(neighbours);
currentCell.destroyWall(dir);
neighbourCell.destroyWall(direction_1.getOppositeDirection(dir));
stack.push(currentCell);
currentCell = neighbourCell;
}
}
/** Export the current grid's cells state. */
exportMatrix() {
if (!this.grid) {
throw new Error("tried to export matrix when grid is uninitialised");
}
return this.grid.exportCells();
}
generatePainter() {
if (!this.grid) {
throw new Error("tried to generate painter when grid is uninitialised");
}
const cells = this.grid.exportCells();
return (options) => {
const { ctx, cellSize, padding } = options;
ctx.lineWidth = 2;
for (let y = 0; y < cells.length; y++) {
for (let x = 0; x < cells[y].length; x++) {
const cell = cells[y][x];
const xAxis = cell.position.x * cellSize + padding / 2;
const yAxis = cell.position.y * cellSize + padding / 2;
ctx.beginPath();
if (y === 0) {
ctx.moveTo(xAxis, yAxis);
ctx.lineTo(xAxis + cellSize, yAxis);
}
if (x === 0) {
ctx.moveTo(xAxis, yAxis + cellSize);
ctx.lineTo(xAxis, yAxis);
}
if (cell.walls.east) {
ctx.moveTo(xAxis + cellSize, yAxis);
ctx.lineTo(xAxis + cellSize, yAxis + cellSize);
}
if (cell.walls.south) {
ctx.moveTo(xAxis + cellSize, yAxis + cellSize);
ctx.lineTo(xAxis, yAxis + cellSize);
}
ctx.stroke();
}
}
};
}
}
exports.Maze = Maze;
//# sourceMappingURL=maze.js.map