Created
August 15, 2021 06:08
-
-
Save luisenriquecorona/2b1fb542f341311fb041358579ef8506 to your computer and use it in GitHub Desktop.
GenerarionAnimated.js
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 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