Created
March 1, 2023 13:17
-
-
Save ekaitz-zarraga/cbbe917fd9d3209fdc12cbae6d81d376 to your computer and use it in GitHub Desktop.
A minimal and dirty example of Conway's Game of Life in javascript
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
let grid = [ | |
[0, 0, 0], | |
[1, 1, 1], | |
[0, 0, 0] | |
]; | |
function vecinasPosibles(x,y,grid){ | |
return [ | |
[x-1,y-1],[x+0,y-1],[x+1,y-1], | |
[x-1,y+0], [x+1,y+0], | |
[x-1,y+1],[x+0,y+1],[x+1,y+1], | |
]; | |
} | |
function enCuadricula(celda){ | |
//let [x,y]=celda; | |
let x = celda[0]; | |
let y = celda[1]; | |
if(x<0 || y<0){ | |
return false; | |
} | |
// TODO: parametrizar para cualquier tamaño | |
if(x>=3|| y>=3){ | |
return false; | |
} | |
return true; | |
} | |
function vecinas(x,y,grid){ | |
let posibles = vecinasPosibles(x,y,grid); | |
return posibles.filter(enCuadricula); | |
} | |
// console.log(vecinas(0,0,grid)); | |
// console.log(vecinas(1,1,grid)); | |
// console.log(vecinas(2,2,grid)); | |
function contarVecinasVivas(x,y,grid){ | |
// TODO: convertirlo a un for para que se entienda | |
let vec = vecinas(x,y,grid); | |
return vec.filter( (pos)=> grid[pos[0]][pos[1]] == 1 ).length; | |
} | |
//console.log(contarVecinasVivas(0,1,grid)); | |
//console.log(contarVecinasVivas(2,2,grid)); | |
function next(grid){ | |
let newGrid = []; | |
for(let i=0; i<grid.length; i++){ | |
newGrid.push(new Array(grid[i].length)); | |
for(let j=0; j<grid[i].length; j++){ | |
// newGrid[i][j] = grid[i][j]; // Esto lo copia sin más | |
let cuenta = contarVecinasVivas(i,j,grid); | |
let viva = grid[i][j] == 1; | |
newGrid[i][j] = 0; | |
if( viva && (cuenta==3 || cuenta==2) ){ | |
// mantenerse | |
newGrid[i][j] = 1; | |
} | |
if( viva && cuenta > 3 ){ | |
// morir por sobrepoblación | |
newGrid[i][j] = 0; | |
} | |
if( !viva && cuenta == 3 ){ | |
// nacer por reproducción | |
newGrid[i][j] = 1; | |
} | |
if( viva && cuenta < 2 ){ | |
// morir por poca población | |
newGrid[i][j] = 0; | |
} | |
} | |
} | |
return newGrid; | |
} | |
let grid1 = next(grid); | |
let grid2 = next(grid1); | |
let grid3 = next(grid2); | |
let grid4 = next(grid3); | |
console.log(grid1); | |
console.log(grid2); | |
console.log(grid3); | |
console.log(grid4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment