-
-
Save jochemstoel/bc10893d4d2c89d39846b4bd1ac2c38a to your computer and use it in GitHub Desktop.
Generate a grid with a random path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildMapWithPath(H, W, L) { | |
let A = [], p = [0,0]; | |
for (let Y = 0; Y < H; Y++) { | |
A[Y] = []; | |
for (let X = 0; X < W; X++) { | |
A[Y].push(0); | |
} | |
} | |
function mark(p) { | |
A[p[0]][p[1]] = 1; | |
} | |
function getPos(y, x) { | |
if (y < H && y > -1 && x < W && x > -1) { | |
return A[y][x]; | |
} | |
return false; | |
} | |
function getTouches(pVar) { | |
let pos = [[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1],[1,0],[1,1]]; | |
return pos.reduce(function (c, b) { | |
if (getPos(pVar[0]+b[0], pVar[1]+b[1]) == 1) { | |
c=c+1; | |
} | |
return c; | |
}, 0); | |
} | |
function getPossible(pVar) { | |
var pos = [[0,1],[-1,0],[1,0],[0,-1]]; | |
return pos.reduce(function (arr, b) { | |
let newPos = getPos(pVar[0] + b[0], pVar[1] + b[1]); | |
if (!newPos) { | |
newPos = [pVar[0] + b[0], pVar[1] + b[1]]; | |
if (getTouches(newPos) <= 2) { | |
if (newPos[0] > -1 && newPos[1] > -1 && newPos[0] < H && newPos[1] < W) { | |
arr.push(newPos); | |
} | |
} | |
} | |
return arr; | |
}, []); | |
} | |
p[0] = Math.floor(Math.random()*p.length); | |
mark(p); | |
for (var I = 0; I < L; I++) { | |
p = getPossible(p); | |
p = p[Math.floor(Math.random()*p.length)]; | |
mark(p); | |
} | |
return A; | |
} | |
// map = buildMapWithPath(20,20, 40); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment