Created
July 29, 2020 17:32
-
-
Save tbranyen/2abc588f9cf5a89440a80d58028dc351 to your computer and use it in GitHub Desktop.
For funsies
This file contains 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
const grid = buildGrid(20, 50, [ | |
(10 * 50) + 20, | |
(10 * 50) + 21, | |
(10 * 50) + 22, | |
(10 * 50) + 23, | |
(10 * 50) + 24, | |
(10 * 50) + 25, | |
(10 * 50) + 26, | |
(10 * 50) + 27, | |
(10 * 50) + 28, | |
]); | |
function buildGrid(rows, columns, active = []) { | |
const cells = []; | |
const totalCells = rows * columns; | |
const grid = { rows, columns, cells }; | |
for (let i = 0; i < totalCells; i++) { | |
cells.push(active.includes(i)); | |
} | |
return grid; | |
} | |
function drawGrid(grid) { | |
const line = []; | |
grid.cells.forEach((cell, i, { length }) => { | |
if (i % grid.columns === 0 || i === length) { | |
if (line.length) console.log(line.join('')); | |
line.length = 0; | |
} | |
if (cell) line.push('🦊') | |
else line.push(' '); | |
}); | |
if (line.length) console.log(line.join('')); | |
} | |
function updateGrid(grid) { | |
grid.cells = grid.cells.map((cell, i) => isAlive(cell, i, grid)); | |
} | |
function isAlive(cell, i, grid) { | |
const top = grid.cells[i - grid.columns]; | |
const topLeft = grid.cells[i - grid.columns - 1]; | |
const topRight = grid.cells[i - grid.columns + 1]; | |
const bottom = grid.cells[i + grid.columns]; | |
const bottomLeft = grid.cells[i + grid.columns - 1]; | |
const bottomRight = grid.cells[i + grid.columns + 1]; | |
const left = grid.cells[i - 1]; | |
const right = grid.cells[i + 1]; | |
const count = top + bottom + left + right + topLeft + topRight + bottomLeft + bottomRight; | |
return cell ? count > 1 && count < 4 : count === 3; | |
} | |
function tick() { | |
console.clear(); | |
updateGrid(grid); | |
drawGrid(grid); | |
} | |
function start() { | |
setInterval(tick, 1000); | |
} | |
drawGrid(grid); | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment