css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div id="grid"></div>
<button id="next">Next generation</button>
<button id="automate">Automate Game</button>
<button id="stop">Stop Automate</button><br />
<button id="reset">New game</button>
            
          
!
            
              /*********************************************************************
 *
 * Conway's Game of Life
 *
 * Ryan Boone
 * falldowngoboone@gmail.com
 *
 * A simple simulation that creates artificial “life” on a grid.
 *
 *
 * Rules:
 *
 * Any live cell with fewer than two or more than three live 
 * neighbors dies.
 *
 * Any live cell with two or three live neighbors lives on to 
 * the next generation.
 *
 * Any dead cell with exactly three live neighbors becomes 
 * a live cell.
 *
 * A neighbor is defined as any adjacent cell, including diagonals
 *
 * Rules are applied to the grid all at once; each cell is
 * observed first, then changes are applied at next generation
 *
 * Use Math.random to initially populate a grid of checkbox fields 
 * and a button to advance to the next generation.
 *
 * Users can check/uncheck checkboxes, and that must be included
 * in the computations
 *
 ********************************************************************/

// grid size as "constants"
var GRID_HEIGHT = 15,
    GRID_WIDTH  = 30,
    GRID_PARENT = document.querySelector('#grid'),
    nextBtn     = document.querySelector('#next'),
    resetBtn    = document.querySelector('#reset'),
    automate   	= document.querySelector('#automate'),
    stopBtn     = document.querySelector('#stop');

// initially hide the stop button
stopBtn.style.display = 'none';

// vectors to track grid position of boxes
function Vector (x, y) {
  this.x = x;
  this.y = y;
}
// adds two vectors together
Vector.prototype.plus = function (other) {
  return new Vector(this.x + other.x, this.y + other.y);
};

// Box object, takes a Vector
function Box (pos) {
  this.pos       = pos;
  this.isAlive   = Math.round(Math.random()) == 1;
  this.neighbors = 0;
}
// flips the box's current status
Box.prototype.changeLiving = function() {
  this.isAlive = !this.isAlive;
};

// Grid object, takes grid height and width
function Grid (height, width) {
  this.height = height;
  this.width  = width;
  this.boxes  = [];
  
  // initialize the boxes array
  for (var i = 0; i < this.height; i++) {
    var row = [];
    
    for (var j = 0; j < this.width; j++) {
      row.push(new Box(new Vector(j, i)));
    }
    // push the row to boxes
    this.boxes.push(row);
  }
}
Grid.prototype.forEach = function(callback) {
  this.boxes.forEach( function(row) {
    row.forEach(callback);
  });
};
// counts the number of living neighbors for each box
Grid.prototype.countNeighbors = function() {
  // cache this for forEach call
  var self = this;
  
  this.forEach(function(box) {
    // neighbor count
    var count = 0;
    
    for (var i = -1; i < 2; i++) {
      for (var j = -1; j < 2; j++) {
        var neighbor = box.pos.plus(new Vector(j, i));
        
        // neighbor must exist in grid, not be the same box,
        // and be alive
        if (neighbor.x >= 0 && neighbor.x < self.width &&
            neighbor.y >= 0 && neighbor.y < self.height &&
            self.boxes[neighbor.y][neighbor.x] != box &&
            self.boxes[neighbor.y][neighbor.x].isAlive) {
          
          count++;
        }
      }
    }
    
    box.neighbors = count;
  });
};

// the game object; in charge of rules and state
function GameOfLife(grid, Display) {
  this.grid    = grid;
  this.display = new Display(GRID_PARENT, this.grid);
  
  // initialize the View (assumes Display.build())
  this.display.build();
}
// run one generation
GameOfLife.prototype.nextGen = function() {
  
  this.grid.countNeighbors();
  
  // change living status based on rules above
  this.grid.forEach(function(box) {
    if ((!box.isAlive && box.neighbors === 3) ||
        (box.isAlive && (box.neighbors < 2 || box.neighbors > 3))) {
      box.changeLiving();
    }
  });
  
  // render the board
  this.display.build();
};

// DOMDisplay object builds the View via DOM objects
function DOMDisplay(parent, grid) {
  this.parent = parent;
  this.grid   = grid;
}
DOMDisplay.prototype.build = function() {
  var parent = this.parent;
  this.clear();
  
  // TODO:
  // Rewrite with Grid.prototype.forEach(box);
  this.grid.boxes.forEach(function(row) {
    var br = document.createElement('br');
    
    row.forEach(function(box) {
      var chBox  = document.createElement('input');
      chBox.type = 'checkbox';
      if (box.isAlive) {
        chBox.setAttribute('checked', true);
      }
      
      // listen for clicks on the checkbox
      chBox.addEventListener('click', function(){
        box.changeLiving();
      });
      
      parent.appendChild(chBox);
    });
    parent.appendChild(br);
  });
};
DOMDisplay.prototype.clear = function() {
  while(this.parent.firstChild) {
    this.parent.removeChild(this.parent.firstChild);
  }
};

// start the game
var game = new GameOfLife(new Grid(GRID_HEIGHT, GRID_WIDTH), DOMDisplay);

// advance the game
nextBtn.addEventListener('click', function() {
  game.nextGen();
});

// reset the game
resetBtn.addEventListener('click', function() {
  game = new GameOfLife(new Grid(GRID_HEIGHT, GRID_WIDTH), DOMDisplay);
});

// NOW WITH AUTOMATION!!!

// need to store an ID for interval so we can clear it
var autoIntervalID;

// automates the game
function automateGame() {
  autoIntervalID = setInterval(function() {
    // explicitly set `this` in nextGen()
    game.nextGen.call(game);
  }, 100);
}

automate.addEventListener('click', function() {
  // switch display of stop and automate buttons
  stopBtn.style.display = '';
  automate.style.display = 'none';
  automateGame();
});

// stops the automation
function haltAutomateGame() {
  clearInterval(autoIntervalID);
}

stopBtn.addEventListener('click', function() {
  // switch display of stop and automate buttons
  automate.style.display = '';
  stopBtn.style.display = 'none';
  haltAutomateGame();
});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console