JSFiddle - React, Tailwind, and code Playground

by tyleretters

HTML

<div class="life"></div>
<div class="next"></div>
<p>generation <span class="generation">0</span>, <a href="#" onclick="seed()">seed</a></p>

CSS

.life {
  width: 100%;
  height: 100%;
  margin: 0 auto 1rem auto;
  display: block;
}

.cell {
  font-size: 64px;
  line-height: 0px;
  width: 20px;
  height: 20px;
  margin: 0;
  padding: 0;
  float: left;
}

.cell[data-toggle='0'] {
  color: #ffffff;
}

.cell[data-toggle='1'] {
  color: #0687f5;
}

.cell-row {
  height: 20px;
}

.next {
  display: none;
}

body {
  font-family: sans-serif;
}

JavaScript

/*
 * Config
 */

var config = {
  generation: 0,
  seed: false,
  x: 10,
  y: 10,
  speed: 1000 // try 200 instead!
}

/*
 * Build HTML
 */
 
function makeGrid(x, y) {
  var out = '';
  for (var iy = y - 1; iy >= 0; iy--) {
    var cells = '';
    for (var ix = x - 1; ix >= 0; ix--) {
      var className = 'x' + ix + 'y' + iy;
      cells += makeCell(className);
    }
    out += makeRow(cells);
  }
  return out;
}

function makeRow(cells) {
  return '<div class="cell-row">' + cells + '</div>';
}

function makeCell(className) {
  return '<div class="cell ' + className + '" data-toggle="0">.</div>';
}

/*
 * Logic
 */

function coinFlip() {
  return (Math.floor(Math.random() * 2) == 0);
}

function toggle(x, y, el = 'life') {
  var cell = document.getElementsByClassName(el)[0].getElementsByClassName('x' + x + 'y' + y)[0];
  cell.dataset.toggle = (cell.dataset.toggle == '0') ? '1' : '0';
}

function isLive(x, y) {
  var cell = document.getElementsByClassName('life')[0].getElementsByClassName('x' + x + 'y' + y)[0];
  if (cell === null) {
    return false;
  }
  return (cell.dataset.toggle == 1) ? true : false;
}

function getNeighbors(x, y) {
  n = (y != config.y - 1); // has northern neighbors
  e = (x != 0); // has eastern neighbors
  s = (y != 0); // has southern neighbors
  w = (x != config.x - 1); // has western neighbors
  count = 0;
  if (n && isLive(x, y + 1)) count++;
  if (n && e && isLive(x - 1, y + 1)) count++;
  if (e && isLive(x - 1, y)) count++;
  if (s && e && isLive(x - 1, y - 1)) count++;
  if (s && isLive(x, y - 1)) count++;
  if (s && w && isLive(x + 1, y - 1)) count++;
  if (w && isLive(x + 1, y)) count++;
  if (n && w && isLive(x + 1, y + 1)) count++;
  return count;
}

/*
 * Any live cell with fewer than two live neighbors dies, as if by under population.
 */
function isUnderPopulated(c) {
  return (c < 2);
}

/*
 * Any live cell with two or three live neighbors lives on to the next generation.
 */
function isHealthy(c) {
  return (c == 2 || c...