JSFiddle - React, Tailwind, and code Playground

by wio_dude

HTML

<input id="r" type="button" value="restart"><br/>
<canvas id="c" width="400" height="500"></canvas>

CSS

canvas {
  border: 1px solid;
}

JavaScript

const ROWS = 50,
      COLS = 40,
      WIDTH = 10,
      HEIGHT = 10,
      UPDATES_PER_FRAME = 1/20

const canvas = document.getElementById('c')
const restart = document.getElementById('r')
const ctx = canvas.getContext('2d')

class ColorCell {
  static random() {
    const values = [...Array(3)].map(() => Math.floor(Math.random() * 256))
    return new ColorCell(...values)
  }
  
  constructor(r, g, b) {
    this.r = r
    this.g = g
    this.b = b
  }
  
  toString() {
    return `#${this.r.toString(16)}${this.g.toString(16)}${this.b.toString(16)}`
  }
}

function center(x) {
  return x < 128 ? x - 127 : x - 128
}

class ColorGrid {
  constructor(rows, cols, init = () => ColorCell.random()) {
    this.rows = rows
    this.cols = cols
    this.colors = [...Array(rows * cols)].map((x, i) => {
      const row = Math.floor(i / this.cols),
            col = i % this.cols
      return init(row, col, this)    
    })
  }
  
  getColor(row, col) {
    return this.colors[row * this.cols + col]
  }
  
  draw(ctx, x, y, w, h) {
    for (let r = 0; r < this.rows; r++) {
      for (let c = 0; c < this.cols; c++) {
        const cell = this.getColor(r, c)
        const y_i = y + r * h
        const x_i = x + c * w
        ctx.fillStyle = cell.toString()
        ctx.fillRect(x_i, y_i, w, h)
      }
    }
  }
  
  update(fn) {
    const newColors = this.colors.map((color, i) => {
      const row = Math.floor(i / this.cols),
            col = i % this.cols
      return fn(color, row, col, this)
    })
    this.colors = newColors
  }
}

function myInit(row, col, grid) {
  const value = Math.floor(Math.random() * 256)
  return new ColorCell(value, value, value)
}

function myUpdate(color, row, col, grid) { 
      let total = 0
      let count = 0
      let r, c
      for (r = row - 1; r <= row + 1; r += 1) {
        for (c = col - 1; c <= col + 1; c += 1) {
          if (!(r === row && c === col) && r >= 0 && c >= 0 && r < grid.rows && c < grid.cols) {
            const cell =...