diff options
-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) |