about summary refs log tree commit diff stats
path: root/js/life.js
blob: 443c79687933f6bc14eb66602eba662079919044 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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)