Skip to content

Instantly share code, notes, and snippets.

@SethVandebrooke
Created November 4, 2020 23:56
Show Gist options
  • Save SethVandebrooke/ebb1caa9df991ebed38fd2c58223c254 to your computer and use it in GitHub Desktop.
Save SethVandebrooke/ebb1caa9df991ebed38fd2c58223c254 to your computer and use it in GitHub Desktop.
Generate a grid with a random path
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