Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <svg class="container"></svg>

<div class="details">
  <h1><a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway's Game of Life</a> in <a href="https://d3js.org/">d3</a></h1>
  
  <p>Click the video to start from a random field</p>
</div>
              
            
!

CSS

              
                .container {
  float: left;
  margin-right: 60px;
  
  .square {
    rect {
      fill: #f0cdaa;
    }
  }
  
  .square.on {
    rect {
      fill: #f0aaad;
    }
  }
}

.details {
  margin-right:60px;
}
              
            
!

JS

              
                // Start by building our model
var fieldWidth = 100,
    fieldHeight = 100,
    
    // Define our visual space
    pxWidth = 300,
    pxHeight = 300,
    pxWidthSquare = pxWidth / fieldWidth,
    pxHeightSquare = pxHeight / fieldHeight,
    
    // How fast does it go?
    msTimestep = 10
;

// Scales to turn field coordinates into rendering coordinates
var x = d3.scale.linear()
	.domain([0, fieldWidth])
	.range([0, pxWidth])

var y = d3.scale.linear()
	.domain([0, fieldHeight])
	.range([0, pxHeight]);

// Get ready...
var svg = d3.select('svg.container')
            .attr('height', pxHeight)
            .attr('width', pxWidth)
					.on('click',  function () { field = randomField() }),
    field = randomField(),
    time = 0;

// Go! Render initial
render(field);

// Then continuously iterate
d3.timer(iterate, msTimestep)
 
function iterate() {
  
  field = createNewGeneration(field)  
  
  render(field)
  
  d3.timer(iterate, msTimestep)
  
  return true; 
}

// Actual d3 rendering. Should not be redrawing the whole thing every time
// But it does reselect everything. Is that healthy?
function render(data) {
  var up = svg.selectAll('g.row').data(data),
      en = up.enter();

  en.append('svg:g')
    .classed('row', true)

  var upSquare = up.selectAll('g.square')
      					.data(function (d) { return d } ),
    	enSquare = upSquare.enter();

  enSquare.append('svg:g')
    .classed('square', true)
      .append('rect')
      .attr('x', function(d, i, j) { return x(i) })
      .attr('y',  function(d, i, j) { return y(j) })
      .attr('width', pxWidthSquare)
      .attr('height', pxHeightSquare);
  
  // Finally, just switch class on and off to visualize binary state
  upSquare.classed('on', function (d) { return d == 1;})
}

// Utility to generate a fresh totally random field
function randomField() {
   return  _.map(d3.range(fieldWidth), function (i) {
      return _.map(d3.range(fieldHeight), function (j) {
        return Math.random() < 0.5 ? 1 : 0
      })
    });
}

// Taken from: http://www.janwillemtulp.com/2011/03/22/tutorial-conways-game-of-life-in-d3/
// and edited by me to not rely on globals/closures so much
function createNewGeneration(states) {
    var nextGen = new Array()
 	var ccx = states.length;
    for (x = 0; x < ccx; x++) {
      	var ccy = states[x].length;
        nextGen[x] = new Array()
        for (y = 0; y < ccy; y++) {
            var ti = y - 1 < 0 ? ccy - 1 : y - 1 // top index
            var ri = x + 1 == ccx ? 0 : x + 1 // right index
            var bi = y + 1 == ccy ? 0 : y + 1 // bottom index
            var li = x - 1 < 0 ? ccx - 1 : x - 1 // left index
 
            var thisState = states[x][y]
            var liveNeighbours = 0
            liveNeighbours += states[li][ti] ? 1 : 0
            liveNeighbours += states[x][ti] ? 1 : 0
            liveNeighbours += states[ri][ti] ? 1 : 0
            liveNeighbours += states[li][y] ? 1 : 0
            liveNeighbours += states[ri][y] ? 1 : 0
            liveNeighbours += states[li][bi] ? 1 : 0
            liveNeighbours += states[x][bi] ? 1 : 0
            liveNeighbours += states[ri][bi] ? 1 : 0
 
            var newState = false
 
            if (thisState) {
                newState = liveNeighbours == 2 || liveNeighbours == 3 ? 1 : 0
            } else {
                newState = liveNeighbours == 3 ? 1 : 0
            }
 
            nextGen[x][y] = newState
        }
    }
 
    return nextGen
}

              
            
!
999px

Console