xxxxxxxxxx
90
class Maze {
constructor(dimX, dimY, cellSize, seed=1) {
this.dim = {
x: dimX,
y: dimY
}
this.grid = [];
this.seed = seed;
this.generate();
}
random() {
let x = Math.sin(this.seed++) * 10000;
return x - Math.floor(x);
}
generate() {
let stack = [];
let current;
for (let i = 0; i < this.dim.x; i++) {
for (let j = 0; j < this.dim.y; j++) {
this.grid.push(new Cell(i, j));
}
}
this.grid[0].visited = true;
current = this.grid[0];
while (this.grid.some(cell => !cell.visited)) {
let neighbour = this.getRandomUnvisitedNeighbour(current);
if (neighbour) {
stack.push(current);
Maze.removeWallBetween(current, neighbour);
current = neighbour;
current.visited = true;
} else if (stack.length != 0) {
current = stack.pop();
} else {
console.error('no stack and no neighbour')
}
}
}
getRandomUnvisitedNeighbour(cell) {
let nIndices = this.neighbourIndices(cell.pos.x, cell.pos.y);
let pos = this.grid.filter(cell => {
for (let pos of nIndices) {
if (cell.pos.x == pos.x && cell.pos.y == pos.y) return true;
}
return false;
}).filter(cell => !cell.visited);
if (pos.length == 0) return null;
return pos[Math.floor(this.random() * pos.length)];
}
static removeWallBetween(a, b) {
if (a.pos.y == b.pos.y) {
if (a.pos.x == b.pos.x + 1) {
a.removeWall(3);
b.removeWall(1);
} else if (a.pos.x == b.pos.x - 1) {
a.removeWall(1);
b.removeWall(3);
}
} else if (a.pos.x == b.pos.x) {
if (a.pos.y == b.pos.y + 1) {
a.removeWall(0);
b.removeWall(2);
} else if (a.pos.y == b.pos.y - 1) {
a.removeWall(2);
b.removeWall(0);
}
}
}
neighbourIndices(i, j) {
let indices = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
if (i + dx >= 0 && i + dx < this.dim.x && j + dy >= 0 && j + dy < this.dim.y && Math.abs(dx) != Math.abs(dy)) {
indices.push({
x: i + dx,
y: j + dy
});
}
}
}
return indices;
}
}