JSFiddle - React, Tailwind, and code Playground

by phloe

CSS

body {
	background-color: #777;
}
canvas {
	transform: scale(2.0);
	transform-origin: 0 0;
	display: block;
}
.map {
	width: calc(5px * 160);
	overflow: hidden;
	min-height: 10px;
}

.map > * {
	width: 5px;
	height: 5px;
	_margin-bottom: 1px;
	_margin-right: 1px;
	background-color: #fff;
	float: left;
	transition: background-color ease-in 0.1s;
}

.alive {
	background-color: #000;
}

button {
	background-color: #999;
	color: #FFF;
	border: 0;
	padding: 10px 20px;
	margin: 10px 10px 10px 0;
	cursor: pointer;
}

JavaScript

var width = 160;
var height = 90;
var spawn = 0.50;
var overpopulation = 3;
var underpopulation = 2;
var spawnpopulation = 3
var items;
var elements;
var fg = "#000";
var bg = "#FFF";
var timer;
var interval = 1000 / 60;
var neighborCoords = [[-1, -1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1]];

var flip = ["odd", "even"];
var frames = 0;
var active = false;

var map = document.createElement("canvas");
map.width = width;
map.height = height;

var imageData, data;

var canvas = map.getContext("2d");

canvas.imageSmoothingEnabled = false;

var play = document.createElement("button");
play.textContent = "Play";

var step = document.createElement("button");
step.textContent = "Step";

var reset = document.createElement("button");
reset.textContent = "Reset";

document.body.appendChild(reset);
document.body.appendChild(step);
document.body.appendChild(play);
document.body.appendChild(map);

play.addEventListener("click", function () {
	if (!active) {
		start();
	}
	else {
		stop();
	}
});

function stop () {
	active = false;
	play.textContent = "Play";
	timer = clearTimeout(timer);
}

function start () {
	active = true;
	play.textContent = "Pause";
	if (!items) {
		game();
	}
	frame();
}

step.addEventListener("click", function () {
	frame(true);
});

reset.addEventListener("click", function () {
	stop();
	game();
});

var game = function () {
	items = makeArray(
		height,
		() => makeArray(
			width,
			() => {
				return {
					odd: (Math.random() >= spawn) ? 1 : 0,
					even: 0,
					dead: 0,
					alive: 0
				};
			}
		)
	);
	
	map.width = width;
	map.height = height;
	
	canvas.fillStyle = fg;
	canvas.fillRect(0, 0, width, height);
	
  	imageData = canvas.getImageData(0, 0, width, height);
	data = imageData.data;
	
	items.forEach(function (row, y) {
		row.forEach(function (cell, x) {
			var offset = (y * width + x) * 4; 
			var value = (alive) ? 0 : ((cell.alive + cell.dead)/4);
			data[offset] = value;
			data[offset + 1] =...