/**
* Conway in plain JS
* (c) 2014 Ben Lesh
* MIT License
*/
// Clear the console, just because I hate it getting
// junked up while I'm playing in JSFiddle
console.clear();
(function (window, document) {
// The Controller for our game;
function Grid(w, h) {
var grid = this;
grid.width = w;
grid.height = h;
// this is the Model, really
grid.rows = null;
// use this to initialize or reset the grid
grid.reset = function () {
var x, y, row;
grid.rows = [];
for (y = 0; y < h; y++) {
row = [];
for (x = 0; x < w; x++) {
row.push(new Cell(x, y));
}
grid.rows.push(row);
}
}
// call it right away to initialize the grid
grid.reset();
// utility to run through all of the cells
// in the grid's rows.
grid.traverse = function (fn) {
var x, y;
var context = {
stop: false
};
outer: for (y = 0; y < grid.height; y++) {
for (x = 0; x < grid.width; x++) {
fn(context, grid.rows[y][x], x, y);
if (context.stop) {
break outer;
}
}
}
}
grid.step = function () {
// first go trough and count live neighbors
// *before* you update each cell.
// Otherwise you'll ruin the live neighbor count
// for the next one.
grid.traverse(function (ctxt, cell) {
cell.examine();
});
// *Now* let's update the cells life status.
grid.traverse(function (ctxt, cell) {
cell.update();
});
};
// The model for an individual cell
function Cell(x, y) {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.