JSFiddle - React, Tailwind, and code Playground
by Keith Henry
HTML
<div id="grid"></div>
CSS
#grid{ position: relative; }
.c { position: absolute; display: block; width: 10px; height:10px; }
.c.a { background-color: #8e8; }
.c.d { background-color: #fefefe; }
JavaScript
var world = []
var torus = false;
function initWorld(x,y){
world = [];
for(var i=0; i < y; i++) {
var row = [];
for(var j=0; j < x; j++) {
row.push(0);
}
world.push(row);
}
}
function getAdjacentCount(state, x, y){
var tl = 0, tm = 0, tr = 0,
ml = 0, mr = 0,
bl = 0, bm = 0, br = 0;
if(y > 0 || torus) {
var tRow = state[y > 0 ? y-1 : state.length - 1];
if(x > 0) {
tl = tRow[x-1];
}
else if(torus) {
tl = tRow[tRow.length-1];
}
tm = tRow[x];
if(x+1 < tRow.length) {
tr = tRow[x+1];
}
else if(torus) {
tr = tRow[0];
}
}
var mRow = state[y];
if(x > 0) {
ml = mRow[x-1];
}
else if(torus) {
ml = mRow[mRow.length-1];
}
if(x+1 < mRow.length) {
mr = mRow[x+1];
}
else if(torus) {
mr = mRow[0];
}
if(y+1 < state.length || torus) {
var bRow = state[y+1 < state.length ? y+1 : 0];
if(x > 0) {
bl = bRow[x-1];
}
else if(torus) {
bl = bRow[bRow.length-1];
}
bm = bRow[x];
if(x+1 < bRow.length) {
br = bRow[x+1];
}
else if(torus) {
br = bRow[0];
}
}
return tl + tm + tr +
ml + mr +
bl + bm + br;
}
function processRules(state) {
var nextState = [];
for(var i=0; i < state.length; i++) {
var currentRow = state[i];
var nextRow = [];
for(var j=0; j < currentRow.length; j++) {
var currentCell = currentRow[j];
var adj = getAdjacentCount(state, j, i);
var nextCell = 0;
if(currentCell === 1) {
// A live cell...
if(adj === 2 || adj === 3) {
...