about summary refs log blame commit diff stats
path: root/js/life.js
blob: 443c79687933f6bc14eb66602eba662079919044 (plain) (tree)









































                                                                                                                                  
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)