xxxxxxxxxx
// Maze generator (randomized Depth-first search)
const cellCount = 101;
const pathWidth = 1.0;
const pathColor = "#FFA300";
const wallColor = "#AB5236";
const PATH = false;
const WALL = true;
let gen;
function setup() {
gen = generateMaze();
const m = min(windowWidth, windowHeight);
createCanvas(m, m);
background(wallColor);
stroke(pathColor);
strokeWeight(pathWidth);
strokeCap(ROUND);
}
function draw() {
const cellSize = width / cellCount;
scale(cellSize);
translate(0.5, 0.5);
gen.next();
}
function* generateMaze() {
const mazeArray = [];
for (let x = 0; x < cellCount; x++) {
mazeArray[x] = [];
for (let y = 0; y < cellCount; y++) {
mazeArray[x][y] = WALL;
}
}
const start = { x: 1, y: 1 };
mazeArray[start.x][start.y] = PATH;
const history = [start];
while (history.length > 0) {
const { x, y } = history.pop();
const directions = shuffle([
{ dx: +1, dy: 0 },
{ dx: 0, dy: +1 },
{ dx: -1, dy: 0 },
{ dx: 0, dy: -1 },
]);
for (const { dx, dy } of directions) {
const newX = x + dx * 2;
const newY = y + dy * 2;
if (
0 < newX && newX < cellCount &&
0 < newY && newY < cellCount &&
mazeArray[newX][newY] === WALL
) {
mazeArray[x + dx][y + dy] = PATH;
mazeArray[newX][newY] = PATH;
history.push({ x: newX, y: newY });
line(x, y, newX, newY);
yield;
}
}
}
}
function mouseClicked() {
setup();
}