Game Of Life

by anoopsuda

HTML

<table id="myTable" border="1" cellpadding=".3" cellspacing="0">
</table>

<p>
  <button type="button" onClick="nextStep()">Next step</button>
  <button type="button" onClick="play()">Play</button>
  <button type="button" onClick="pause()">Pause</button>
  <button type="button" onClick="clearAll()">Clear all</button>
  <button type="button" onClick="random()">Random</button>
  <input id="timer" type="range" min="100" max="1000">
  <span id="timerLabel"></span>
</p>

CSS

table {border:none; border-collapse: separate;
    border-spacing: 2px;}
	
	table td {border:solid 1px #ccc; border-radious:5px;}
	table td  input {border:none; opacity:0;}

JavaScript

const COLUMNS = 20
const ROWS = 20

const myTable = document.getElementById("myTable")
const matrix = []

let running = false
let nextStepTime = 0

const isInsideMatrix = (x, y) => {
  return (x >= 0 && y >= 0 && x < ROWS && y < COLUMNS)
}

const checkCell = (x, y) => {
  return isInsideMatrix(x, y) && matrix[x][y].querySelector('input').checked
}


const clearAll = () => {
running = false
const tds = document.getElementsByTagName("td")
const ck = document.getElementsByTagName("input")
const totalcells = tds.length

  for (let k = 0; k <= totalcells; k++){  
    ck[k].checked = false
    tds[k].style.background = "#fff"   
  }
  
   
  
}

const play = () => {
  if (!running) {
    running = true
    step()
  }
}

const pause = () => {
  running = false
}

// loop (30 FPS)
const step = () => {
  const now = Date.now()
  const timer = parseInt(document.getElementById('timer').value)
  if (running) {
    // it’s time for the next step?
    if (now >= nextStepTime) {
      nextStep()
      nextStepTime = now + timer
    }
    setTimeout(step, 33)
  }
  document.getElementById('timerLabel').innerText = timer
}

const random = () => {
  for (let i = 0; i < ROWS; i++) {
    for (let j = 0; j < COLUMNS; j++) {
      const cell = matrix[i][j]
      const input = cell.querySelector('input')
      input.checked = parseInt(Math.random() * 2) ? false : true
      cell.style.backgroundColor = input.checked ? '#a100ff' : 'white'
    }
  }
}

// Next step function
//
const nextStep = () => {
  for (let i = 0; i < ROWS; i++) {
    for (let j = 0; j < COLUMNS; j++) {
      const cell = matrix[i][j]

      let neighbors = 0
      // N
      if (checkCell(i - 1, j)) {
        neighbors++
      }
      // NE
      if (checkCell(i - 1, j + 1)) {
        neighbors++
      }
      // E
      if (checkCell(i, j + 1)) {
        neighbors++
      }
      // SE
      if (checkCell(i + 1, j + 1)) {
        neighbors++
      }
      // S
      if (checkCell(i + 1, j)) {
        neighbors++
 ...