-
Notifications
You must be signed in to change notification settings - Fork 303
/
maze.js
45 lines (38 loc) · 1.24 KB
/
maze.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
function generateSquareMaze(dimension) {
function iterate(field, x, y) {
field[x][y] = false;
while(true) {
directions = [];
if(x > 1 && field[x-2][y] == true) {
directions.push([-1, 0]);
}
if(x < field.dimension - 2 && field[x+2][y] == true) {
directions.push([1, 0]);
}
if(y > 1 && field[x][y-2] == true) {
directions.push([0, -1]);
}
if(y < field.dimension - 2 && field[x][y+2] == true) {
directions.push([0, 1]);
}
if(directions.length == 0) {
return field;
}
dir = directions[Math.floor(Math.random()*directions.length)];
field[x+dir[0]][y+dir[1]] = false;
field = iterate(field, x+dir[0]*2, y+dir[1]*2);
}
}
// Initialize the field.
var field = new Array(dimension);
field.dimension = dimension;
for(var i = 0; i < dimension; i++) {
field[i] = new Array(dimension);
for (var j = 0; j < dimension; j++) {
field[i][j] = true;
}
}
// Gnerate the maze recursively.
field = iterate(field, 1, 1);
return field;
}