-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmazeGenerate.ts
41 lines (30 loc) · 1003 Bytes
/
mazeGenerate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import type ObservableNode from '../utils/ObservableNode';
const recursive = (current: ObservableNode, visited: Set<ObservableNode>) => {
if (visited.has(current)) {
return;
}
visited.add(current);
current.blockType = 'block';
const neighbors = current
.getNeighborsThroughWall()
.filter((x) => !visited.has(x[0]));
while (neighbors.length > 0) {
const i = Math.floor(Math.random() * neighbors.length);
const [neighbor, wallBetween] = neighbors[i];
neighbors.splice(i, 1);
if (visited.has(neighbor)) {
continue;
}
wallBetween.blockType = 'block';
recursive(neighbor, visited);
}
};
export default function mazeGenerate(gridNodes: ObservableNode[][]) {
const visited = new Set<ObservableNode>();
gridNodes.forEach((x) => x.forEach((y) => (y.blockType = 'wall')));
for (let y = gridNodes.length - 1; y >= 0; y -= 2) {
for (let x = 0; x < gridNodes[y].length; x += 2) {
recursive(gridNodes[y][x], visited);
}
}
}