MCPcopy
hub / github.com/Vishal-raj-1/Awesome-JavaScript-Projects / newMaze

Function newMaze

assets/js/mazeGenerator.js:1–74  ·  view source on GitHub ↗
(x, y)

Source from the content-addressed store, hash-verified

1function newMaze(x, y) {
2
3 // Initializing
4 var totalCells = x * y;
5 var cells = new Array();
6 var unvis = new Array();
7 for (var i = 0; i < y; i++) {
8 cells[i] = new Array();
9 unvis[i] = new Array();
10 for (var j = 0; j < x; j++) {
11 cells[i][j] = [0, 0, 0, 0];
12 unvis[i][j] = true;
13 }
14 }
15
16 var currentCell = [Math.floor(Math.random() * y), Math.floor(Math.random() * x)];
17 var path = [currentCell];
18 unvis[currentCell[0]][currentCell[1]] = false;
19 var visited = 1;
20
21 while (visited < totalCells) {
22
23 var pot = [[currentCell[0] - 1, currentCell[1], 0, 2],
24 [currentCell[0], currentCell[1] + 1, 1, 3],
25 [currentCell[0] + 1, currentCell[1], 2, 0],
26 [currentCell[0], currentCell[1] - 1, 3, 1]];
27 var neighbors = new Array();
28
29
30 for (var l = 0; l < 4; l++) {
31 if (pot[l][0] > -1 && pot[l][0] < y && pot[l][1] > -1 && pot[l][1] < x && unvis[pot[l][0]][pot[l][1]]) { neighbors.push(pot[l]); }
32 }
33
34
35 if (neighbors.length) {
36
37 next = neighbors[Math.floor(Math.random() * neighbors.length)];
38
39
40 cells[currentCell[0]][currentCell[1]][next[2]] = 1;
41 cells[next[0]][next[1]][next[3]] = 1;
42
43
44 unvis[next[0]][next[1]] = false;
45 visited++;
46 currentCell = [next[0], next[1]];
47 path.push(currentCell);
48 }
49
50 else {
51 currentCell = path.pop();
52 }
53 }
54 var answer = "";
55 for (var i = 0; i < cells.length; i++) {
56 $('#maze > tbody').append("<tr>");
57 // answer += "<tr></tr>";
58 for (var j = 0; j < cells[i].length; j++) {
59 var selector = i + "-" + j;
60 // answer += "<td id='"+selector+"'>&nbsp;</td>";

Callers

nothing calls this directly

Calls 1

$Function · 0.70

Tested by

no test coverage detected