-
Notifications
You must be signed in to change notification settings - Fork 11
/
depthfirstsearch.js
68 lines (63 loc) · 1.96 KB
/
depthfirstsearch.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
function DepthFirstSearchGenerator(topology, sizeX, sizeY) {
this.maze = new Maze(topology, sizeX, sizeY, {
initialRoomColor: Maze.FILLED,
initialEdgeColor: Maze.FILLED,
initialVertexColor: Maze.FILLED,
});
// room,edge,room,edge, ..., room
this.stack = [];
this.doneRooms = [];
this.startedYet = false;
this.vectors = null;
}
DepthFirstSearchGenerator.CONSIDERING = "#8888ff";
DepthFirstSearchGenerator.prototype.getOptions = function() {
var self = this;
if (!self.startedYet) {
// pick a starting room
return {
type: "room",
values: util.range(self.maze.getRoomCount()),
};
}
if (self.stack.length === 0) return null;
// offer a selection of directions to travel from here.
var room = self.stack[self.stack.length - 1];
self.vectors = self.maze.roomToVectors(room).filter(function(vector) {
// make sure we're not creating a loop
if (self.maze.roomColors[vector.room] !== Maze.FILLED) return false;
return true;
});
return {
type: "vector",
values: self.vectors,
};
};
DepthFirstSearchGenerator.prototype.doOption = function(index) {
if (!this.startedYet) {
// the starting room
var startingRoom = index;
this.stack.push(startingRoom);
this.maze.roomColors[startingRoom] = DepthFirstSearchGenerator.CONSIDERING;
this.startedYet = true;
return;
}
if (this.vectors.length !== 0) {
// go in the specified direction
var vector = this.vectors[index];
this.maze.edgeColors[vector.edge] = DepthFirstSearchGenerator.CONSIDERING;
this.maze.roomColors[vector.room] = DepthFirstSearchGenerator.CONSIDERING;
this.stack.push(vector.edge);
this.stack.push(vector.room);
} else {
// back out
var room = this.stack[this.stack.length - 1];
this.maze.roomColors[room] = Maze.OPEN;
this.stack.pop();
// clean up edge color
if (this.stack.length > 0) {
var edge = this.stack.pop();
this.maze.edgeColors[edge] = Maze.OPEN;
}
}
};