-
Notifications
You must be signed in to change notification settings - Fork 2
/
solve.js
86 lines (77 loc) · 2.43 KB
/
solve.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
window.solve = function() {
window.maze.runAlgorithm(maze.DFSSolve);
};
Maze.prototype.DFSSolve = function(){
maze = window.maze;
if (render_steps){
maze.DrawScreen();
}
try{
var stacktop = maze.cellStack.pop();
//If we're at the destination, we can abort
if((stacktop[0] === maze.solve_end_x) && (stacktop[1] === maze.solve_end_y)){
return;
}
else{
anim_request = window.requestAnimFrame(maze.DFSSolve);
}
var row = stacktop[0];
var col = stacktop[1];
var node = maze.nodes[row][col];
node.stat = visited;
var neighbours = [];
if ( (row > 0) && !(node.IsStanding(north))
&& (maze.nodes[row-1][col].stat === untouched)){
neighbours.push(north);
}
if ( (row < grid_rows-1) && !(node.IsStanding(south))
&& (maze.nodes[row+1][col].stat === untouched)){
neighbours.push(south);
}
if ( (col > 0) && !(node.IsStanding(west))
&& (maze.nodes[row][col-1].stat === untouched)){
neighbours.push(west);
}
if ( (col < grid_cols-1) && !(node.IsStanding(east))
&& (maze.nodes[row][col+1].stat === untouched)){
neighbours.push(east);
}
// Pop off the stack if there are no neighbours
if (neighbours.length === 0){
stacktop = maze.cellStack.pop();
maze.nodes[stacktop[0]][stacktop[1]].stat = current;
maze.cellStack.push(stacktop);
return;
}
var index = Math.floor(Math.random()*neighbours.length);
var direction = neighbours[index];
var new_loc = [0, 0];
if (direction & north){
new_loc = [row-1, col];
}
if (direction & south){
new_loc = [row+1, col];
}
if (direction & east){
new_loc = [row, col+1];
}
if (direction & west){
new_loc = [row, col-1];
}
node.stat = stacked;
maze.cellStack.push(stacktop);
maze.cellStack.push(new_loc);
maze.nodes[new_loc[0]][new_loc[1]].stat = current;
}
catch(e){
if((e instanceof TypeError) && (e.message === "stacktop is undefined")){
return;
}
else{
throw e;
}
}
};
window.DFSGen = function() {
window.maze.runAlgorithm(maze.DFSGenerate);
};