-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursive-backtracker.js
50 lines (41 loc) · 1.01 KB
/
recursive-backtracker.js
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
42
43
44
45
46
47
48
49
50
let maze = null
let current = null
let stack = []
const drawBacktrackingLine = () => {
stroke(150)
const center = cell => {
return {
x: cell.x + cell.size / 2,
y: cell.y + cell.size / 2
}
}
for (let i = 0; i < stack.length - 1; i++) {
const a = center(stack[i])
const b = center(stack[i + 1])
line(a.x, a.y, b.x, b.y)
}
}
function setup() {
grid = createGrid()
current = pickMiddle(grid)
}
function draw() {
background(51)
grid.cells.forEach(drawWalls)
drawBacktrackingLine()
current.visited = true
const next = pickRandom(getNeighbours(grid, current).filter(x => !x.visited))
if (next) {
colorCell([0, 0, 255], current)
next.visited = true
stack.push(current)
connect(current, next)
current = next
} else if (stack.length > 0) {
colorCell([0, 0, 255], current)
current = stack.pop()
} else {
current = null
noLoop()
}
}