MCPcopy Create free account
hub / github.com/codename-co/stack / generateSquareMaze

Function generateSquareMaze

hub/astray/maze.js:1–43  ·  view source on GitHub ↗
(dimension)

Source from the content-addressed store, hash-verified

1function generateSquareMaze(dimension) {
2
3 function iterate(field, x, y) {
4 field[x][y] = false;
5 while(true) {
6 directions = [];
7 if(x > 1 && field[x-2][y] == true) {
8 directions.push([-1, 0]);
9 }
10 if(x < field.dimension - 2 && field[x+2][y] == true) {
11 directions.push([1, 0]);
12 }
13 if(y > 1 && field[x][y-2] == true) {
14 directions.push([0, -1]);
15 }
16 if(y < field.dimension - 2 && field[x][y+2] == true) {
17 directions.push([0, 1]);
18 }
19 if(directions.length == 0) {
20 return field;
21 }
22 dir = directions[Math.floor(Math.random()*directions.length)];
23 field[x+dir[0]][y+dir[1]] = false;
24 field = iterate(field, x+dir[0]*2, y+dir[1]*2);
25 }
26 }
27
28 // Initialize the field.
29 var field = new Array(dimension);
30 field.dimension = dimension;
31 for(var i = 0; i < dimension; i++) {
32 field[i] = new Array(dimension);
33 for (var j = 0; j < dimension; j++) {
34 field[i][j] = true;
35 }
36 }
37
38 // Gnerate the maze recursively.
39 field = iterate(field, 1, 1);
40
41 return field;
42
43}
44
45

Callers

nothing calls this directly

Calls 1

iterateFunction · 0.85

Tested by

no test coverage detected