@miketmoore/maze-generator
Version:
This is a javascript library, written in TypeScript that generates a maze data structure.
42 lines (41 loc) • 1.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.carveRecursiveBacktracking = void 0;
const rand_1 = require("./rand");
function carveRecursiveBacktracking(grid) {
const coord = grid.getRandCoord();
_carveRecursiveBacktracking(grid, [coord]);
}
exports.carveRecursiveBacktracking = carveRecursiveBacktracking;
function _carveRecursiveBacktracking(carveableGrid, history) {
const coord = history[history.length - 1];
// get list of walls not carved yet, that point to adjacent cells that have not been visited yet
const cell = carveableGrid.getCell(coord);
if (!cell) {
throw new Error('cell not found');
}
const availableWalls = carveableGrid.getAvailableCellWalls(cell, coord);
if (availableWalls.length === 0) {
if (history.length >= 2) {
history.pop();
_carveRecursiveBacktracking(carveableGrid, history);
return;
}
return;
}
const wallIndex = rand_1.randInRange(0, availableWalls.length);
const availableWall = availableWalls[wallIndex];
carveableGrid.carveCellWall(coord, availableWall);
const adjacentCoord = carveableGrid.getAdjacentCoord(availableWall, coord);
if (adjacentCoord) {
const adjacentCell = carveableGrid.getAdjacentCell(availableWall, coord);
if (adjacentCell) {
if (!adjacentCell.isVisited()) {
const oppDir = adjacentCell.getOppositeDirection(availableWall);
carveableGrid.carveCellWall(adjacentCoord, oppDir);
history.push(adjacentCoord);
_carveRecursiveBacktracking(carveableGrid, history);
}
}
}
}