Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created August 15, 2021 06:08
Show Gist options
  • Save luisenriquecorona/2b1fb542f341311fb041358579ef8506 to your computer and use it in GitHub Desktop.
Save luisenriquecorona/2b1fb542f341311fb041358579ef8506 to your computer and use it in GitHub Desktop.
GenerarionAnimated.js
function newGeneration (cells) {
const nextGeneration = []
for (let i = 0; i < cells.length; i++) {
const nextGenerationRow = []
for (let j = 0; j < cells[i].length; j++) {
// Get the number of living neighbours
let neighbourCount = 0
if (i > 0 && j > 0) neighbourCount += cells[i - 1][j - 1]
if (i > 0) neighbourCount += cells[i - 1][j]
if (i > 0 && j < cells[i].length - 1) neighbourCount += cells[i - 1][j + 1]
if (j > 0) neighbourCount += cells[i][j - 1]
if (j < cells[i].length - 1) neighbourCount += cells[i][j + 1]
if (i < cells.length - 1 && j > 0) neighbourCount += cells[i + 1][j - 1]
if (i < cells.length - 1) neighbourCount += cells[i + 1][j]
if (i < cells.length - 1 && j < cells[i].length - 1) neighbourCount += cells[i + 1][j + 1]
// Decide whether the cell is alive or dead
const alive = cells[i][j] === 1
if ((alive && neighbourCount >= 2 && neighbourCount <= 3) || (!alive && neighbourCount === 3)) {
nextGenerationRow.push(1)
} else {
nextGenerationRow.push(0)
}
}
nextGeneration.push(nextGenerationRow)
}
return nextGeneration
}
/*
* utility function to display a series of generations in the console
*/
async function animate (cells, steps) {
/*
* utility function to print one frame
*/
function printCells (cells) {
console.clear()
for (let i = 0; i < cells.length; i++) {
let line = ''
for (let j = 0; j < cells[i].length; j++) {
if (cells[i][j] === 1) line += '\u2022'
else line += ' '
}
console.log(line)
}
}
printCells(cells)
for (let i = 0; i < steps; i++) {
await new Promise(resolve => setTimeout(resolve, 250)) // sleep
cells = newGeneration(cells)
printCells(cells)
}
}
// Define glider example
const glider = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
animate(glider, 16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment