Game of Life (d3.js)

by Ryan

HTML

<script src="https://d3js.org/d3.v3.min.js"></script>
<button id="start">Start</button>
<div id="epoch"></div>
<div id="container"></div>

CSS

rect.cell {
    fill: white;
    stroke: black;
    stroke-width: 0.5px;
}

JavaScript

/*
/ README
/ This is a basic implementation of Conway's Game of Life
/   http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
/
/ This implementation is built using D3.js (d3js.org)
/ and features a game board that wraps in both dimensions,
/ so it exhibits finite extent, but no boundaries. The simulation
/ continues until two consecutive boards are identical.
*/

// Basic control variables
var gridSize = 40;     // The number of cells in each dimension of the 2-d world
var boxSize = 10;      // The size (in pixels) to draw each cell
var currentEpoch = 0;  // The current epoch of the simulation (increments over time)
var epochTime = 200;   // Epoch duration (ms)
var transition = 50;  // Animation effect duration (ms)

/*
/ The data array, storing the alive/dead state of every cell
/ Stored as a 1d array where each row is stored in sequence
/ Initialized randomly to living and dead (true/false)
*/
var data = [];
for(var i=0; i<gridSize*gridSize; i++){
    data.push((Math.random() > 0.5));
}

// Create the initial structure of the game board (using SVG rectangles)
var svg = d3.select("#container").append("svg")
    .attr("height", boxSize*gridSize)
    .attr("widht", boxSize*gridSize)
    .append("g");

// Get the div for the epoch indicator
var epochDiv = d3.select("div#epoch");

// Bind the data to svg rects (this will draw the board)
var cell = svg.selectAll("rect.cell").data(data);
cell.enter().append("rect")
    .attr("class", "cell")
    .attr("x", function(d, i) { return (i%gridSize)*boxSize; } )
    .attr("y", function(d, i) { return (Math.floor(i/gridSize))*boxSize; } )
    .attr("width", boxSize)
    .attr("height", boxSize);

// Redraw function is responsible for updating the state of the dom
var redraw = function(){
    /*
    / Select all the rectangles and update their fill color based 
    / on whether they are alive (green) or dead (white)
    */
    svg.selectAll("rect.cell")
        .transition().duration(transition)
        .style("fill",...