Skip to content

Instantly share code, notes, and snippets.

@jimmy-collazos
Created November 19, 2019 23:28
Show Gist options
  • Save jimmy-collazos/055fb2e80163288fce5ff29708c509c4 to your computer and use it in GitHub Desktop.
Save jimmy-collazos/055fb2e80163288fce5ff29708c509c4 to your computer and use it in GitHub Desktop.
El juego de la vida
function getFactory(ls) {
return function(x, y) {
return Array.isArray(ls[y]) ? (ls[y][x] === undefined && [] || [ls[y][x]]) : [];
}
}
function getNeighbors(x, y, ls){
const get = getFactory(ls);
return [
get(x-1, y+1), get(x, y+1), get(x+1, y+1),
get(x-1, y), get(x, y), get(x+1, y),
get(x-1, y-1), get(x, y-1), get(x+1, y-1)
].reduce((a, b) => a.concat(b));
}
function generate(w, h){
return Array(h).fill(0).map(_ => Array(w).fill(0));
}
function random() {
const f = Math.floor, r = Math.random, a = arguments;
switch(a.length){
case 0: return f(r()); break;
case 1: return f(r() * (a[0] + 1));break;
case 2: return f(r() * (a[1] - a[0] + 1)) + a[0];break;
}
};
function redraw(ls){
const newLs = ls.map(r => [...r]);
for (let y = 0; y < ls.length; y++) {
for (let x = 0; x < ls[y].length; x++) {
let isLive = !!ls[y][x];
// en teoría aquí suma la cantidad de vecinos; aunque on lo tengo claro
let neighborsN = getNeighbors(x, y, ls).reduce((a, b) => a + b);
if(isLive){
//
if(!(neighborsN == 2 || neighborsN == 3)){
newLs[y][x] = 0;
}
} else if(neighborsN === 3) {
newLs[y][x] = 1;
}
}
}
return newLs;
}
let board = generate(10, 10);
// Array(5).fill(0).forEach(_ => (board[random(9)][random(9)] = 1)); // add seed
board[3][3] = 1;
board[4][3] = 1;
board[5][3] = 1;
(function run () {
setInterval(() => {
console.clear();
console.log(board);
board = redraw(board);
run();
}, 1500);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment