Skip to content

Instantly share code, notes, and snippets.

@visnup
Last active December 17, 2015 12:08
Show Gist options
  • Save visnup/5607166 to your computer and use it in GitHub Desktop.
Save visnup/5607166 to your computer and use it in GitHub Desktop.
Conway's Game of Life

Live example at http://bl.ocks.org/visnup/5607166. Move the mouse to pan and click to stop.

From Wikipedia:

The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead. Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one). The rules continue to be applied repeatedly to create further generations.

<style type="text/css">
body { text-align: center }
svg { margin: 0 auto }
</style>
<body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.4.2/d3.min.js"></script>
<script>
(function() {
var gosper = [
' x',
' x x',
' xx xx xx',
' x x xx xx',
'xx x x xx',
'xx x x xx x x',
' x x x',
' x x',
' xx'
]
, rPentomino = [
' xx',
'xx',
' x'];
var cells = init(rPentomino);
var width = 900, cx = width/2
, height = 500, cy = height/2
, center = [ cx, cy ]
, svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
.append('g').data([ center ])
.attr('transform', function(d) {
return 'translate(' + d + ')'
})
, circles = svg.selectAll('circle');
var lastEvent;
d3.select('svg')
.on('mousemove', function() { lastEvent = d3.event })
.on('mouseup', function() { lastEvent = null });
(function step() {
render();
// next generation
var nextCells = {}
, coords = Object.keys(cells)
, empties = []
, i, n, cell;
for (i = 0; i < coords.length; i++) {
cell = cells[coords[i]];
n = neighbors(cell, empties);
if (n === 2 || n === 3)
nextCells[cell] = cell;
}
for (i = 0; i < empties.length; i++) {
cell = empties[i];
n = neighbors(cell);
if (n === 3)
nextCells[cell] = cell;
}
cells = nextCells;
// pan
if (lastEvent) {
center[0] += (cx - lastEvent.x) / 32;
center[1] += (cy - lastEvent.y) / 32;
}
setTimeout(step, 100);
})();
function init(rows) {
var map = {}, columns;
for (var i = 0; i < rows.length; i++) {
columns = rows[i].split('');
for (var j = 0; j < columns.length; j++)
if (columns[j] !== ' ')
map[[j, i]] = [j, i];
}
return map;
}
function neighbors(coords, empties) {
var n = 0, dx, dy, dc;
for (dx = -1; dx <= 1; dx++) {
for (dy = -1; dy <= 1; dy++) {
if (dx === 0 && dy === 0) continue;
dc = [coords[0] + dx, coords[1] + dy];
if (cells[dc.join(',')])
n++;
else if (empties)
empties.push(dc);
}
}
return n;
}
function render() {
svg
.transition()
.attr('transform', function(d) { return 'translate(' + d + ')' });
circles = circles
.data(d3.map(cells).values(), function(c) { return c })
circles.enter().append('circle')
.attr('cx', function(c) { return c[0] * 10 })
.attr('cy', function(c) { return c[1] * 10 })
.attr('r', 1e-6)
.transition().duration(200)
.attr('r', 6)
circles.exit().transition().duration(300)
.attr('r', 1e-6)
.remove();
}
})();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment