Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created February 26, 2020 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sylvainpolletvillard/78cf32be02361de12607be736420b0f4 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/78cf32be02361de12607be736420b0f4 to your computer and use it in GitHub Desktop.
quick game of life
const parseGrid = ([str]) => str
.split('\n')
.map(row => row.trim())
.filter(row => row.length > 0)
.map(row => row.split('').map(char => char !== '.'))
const formatGrid = rows => rows
.map(row => row.map(cell => cell ? '#' : '.').join(''))
.join('\n')
const calcNextGridState = grid => grid.map((row, y) => row.map((cell, x) => calcNextCellState(grid, cell, x, y)))
const calcNextCellState = (grid, cell, x, y) => {
const neighbours = [
[x - 1, y - 1],
[x - 1, y],
[x - 1, y + 1],
[x, y - 1],
[x, y + 1],
[x + 1, y - 1],
[x + 1, y],
[x + 1, y + 1]
]
const nbNeighboursAlive = neighbours
.filter(([x, y]) => x >= 0 && y >= 0 && y < grid.length && x < grid[y].length && grid[y][x])
.length
// une cellule morte possédant exactement trois voisines vivantes devient vivante
if (!cell && nbNeighboursAlive === 3) return true
// une cellule vivante possédant deux ou trois voisines vivantes le reste,
if (cell && (nbNeighboursAlive === 2 || nbNeighboursAlive === 3)) return true;
// sinon elle meurt
return false
}
(function loop(grid, t = 1) {
const out = formatGrid(grid)
console.log(`Turn ${t}\n${out}`)
if (t < 100 && out.includes('#')) setTimeout(() => {
loop(calcNextGridState(grid), ++t)
}, 1000)
})(parseGrid`
....................
....................
....................
....................
......#.#...........
......#.#.#.........
......#####.........
....................
....................
....................
`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment