diff options
author | elioat <elioat@tilde.institute> | 2024-06-07 21:38:09 -0400 |
---|---|---|
committer | elioat <elioat@tilde.institute> | 2024-06-07 21:38:09 -0400 |
commit | ee9371073bf7b7f56fb884ee4cce5da13dc35ceb (patch) | |
tree | 29b5c024c3d32f8e8f05bfd32f000d61f54d1a2b /js | |
parent | f5c151b9379f10fbf6c13bf40d645fe6999f894f (diff) | |
download | tour-ee9371073bf7b7f56fb884ee4cce5da13dc35ceb.tar.gz |
*
Diffstat (limited to 'js')
-rw-r--r-- | js/life.js | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/js/life.js b/js/life.js new file mode 100644 index 0000000..443c796 --- /dev/null +++ b/js/life.js @@ -0,0 +1,42 @@ +const initialBoard = [ + [0, 1, 0], + [0, 0, 1], + [1, 1, 1], + [0, 0, 0] +] + +const getNextState = (board) => { + const rows = board.length + const cols = board[0].length + + const countLiveNeighbors = (board, x, y) => { + return [-1, 0, 1].reduce((acc, dx) => + acc + [-1, 0, 1].reduce((acc, dy) => + (dx === 0 && dy === 0) || x + dx < 0 || y + dy < 0 || x + dx >= rows || y + dy >= cols ? acc : acc + board[x + dx][y + dy] + , 0) + , 0) + } + + return board.map((row, x) => + row.map((cell, y) => { + const liveNeighbors = countLiveNeighbors(board, x, y) + return (cell === 1 && (liveNeighbors === 2 || liveNeighbors === 3)) || (cell === 0 && liveNeighbors === 3) ? 1 : 0 + }) + ) +} + +const printBoard = (board) => { + console.clear() + console.log(board.map(row => row.join(' ')).join('\n')) +} + +const runGame = async (initialBoard, generations) => { + let board = initialBoard + for (let i = 0; i < generations; i++) { + printBoard(board) + board = getNextState(board) + await new Promise(resolve => setTimeout(resolve, 500)) // wait before printing the next step. + } +} + +runGame(initialBoard, 5) |