Conway's Game of Life

Conway's Game of Life algorithm in Javascript

by Daman Daman

HTML

<canvas id="c" width="1512" height="1512"></canvas>

JavaScript

const canvas = document.getElementById('c').getContext('2d')
canvas.fillStyle = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
const ceilSize = 8
const gridSize = ceilSize * ceilSize // 64
const cWidth = ceilSize * gridSize // 512
const cHeight = ceilSize * gridSize // 512

function draw(cells) {
  canvas.clearRect(0, 0, cWidth, cHeight)
  cells.forEach((row, x) => {
    row.forEach((cell, y) => {
      canvas.beginPath()
      canvas.rect(x * ceilSize, y * ceilSize, ceilSize, ceilSize)
      if (cell) canvas.fill()
    })
  })
}

function countNeighbours(x, y, cells) {
  let neighbours = 0
  for (let h = -1; h <= +1; h++) {
    for (let v = -1; v <= +1; v++) {
      if (h == 0 && v == 0) continue
      if (cells[x + h] && cells[x + h][y + v]) neighbours++
    }
  }
  return neighbours
}

function nextGeneration(cells) {
  return cells.map((row, x) => row.map((cell, y) => {
    const neighbours = countNeighbours(x, y, cells)
    return neighbours === 3 || (cell && neighbours === 2)
  }))
}

function update(cells) {
  const newCells = nextGeneration(cells)
  draw(newCells)
  setTimeout(() => update(newCells), 70)
}

function init() {
  const cells = Array(gridSize).fill().map(() =>
    Array(gridSize).fill().map(() => Math.random() >= 0.8)
  )
  update(cells)
}

init()