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

              
                
<p>
    <button id="Start">Start</button>
    <button id="Clear">Clear</button>
    <button id="Random">Randomize</button>
    <label for="Metabolism">Metabolism</label>
    <input id="Metabolism" type="text" size="3" placeholder="100"/>
</p>
<p>
    This is a Backbone.js implementation of <a href="http://en.wikipedia.org/wiki/Conway_game_of_life">Conway's Game of Life</a>. On
    <a href="https://github.com/SimpleAsCouldBe/gameOfLife">github</a>.
</p>
<div id="GameOfLife" class="gameOfLife"></div>

              
            
!

CSS

              
                $dark: #20150C
$subtleOnDark: #30251C
$legible: #C0B5AC
$quiet: #50453C
$blue: #94BEE6
$green: #C2DD96


body
  font-family: Helvetica, helvetica, 'helvetica neue', Verdana, sans-serif
  line-height: 1.4
  background-color: $dark
  color: $legible
p
  font-size: 12px
  color: $quiet
  margin: 0 0 10px 0
label
  color: $legible
a,
a:visited
  color: $quiet

br
  clear: both

.gameOfLife
  position: relative
  line-height: 0 // Otherwise the cells stay at minimum text height apart
  user-select: none
  -moz-user-select: none
  -webkit-user-select: none
.startBtn
  margin-bottom: 10px

// The 'Living' Cells
.gameOfLife i
  display: block
  position: relative
  background-color: $subtleOnDark
  //box-shadow: 0 0 0 2px $subtleOnDark
  float: left
  border-radius: 7px
  width: 14px
  height: 14px
  cursor: pointer
.running .gameOfLife i
  -webkit-transition: all 0.1s ease-out
  -moz-transition: all 0.1s ease-out
  -transition: all 0.1s ease-out

.gameOfLife i.alive
  background-color: $green
  //box-shadow: 0 0 0 2px $green
  z-index: 1 //live cells should be above others
.gameOfLife i:hover
  background-color: $blue
  //box-shadow: 0 0 0 2px $blue
  z-index: 2 //hover cells should be above everyone
.gameOfLife i.alive:hover
  background-color: $green + 50
  box-shadow: 0 0 0 1px $green + 50
  z-index: 2 //hover cells should be above everyone



              
            
!

JS

              
                
// ----------------------------- The Living Cell
;(function(window, _, Backbone){
    var Model, View

    View = Backbone.View.extend({
        tagName: 'i',
        events: {
            'touchstart': 'cellClicked',
            'mousedown': 'cellClicked',
            'mouseover': 'mouseover',
            'mouseout': 'mouseout',
            'touchend': 'mouseout'
        },
        initialize: function () {
            //_.bindAll(this)
            this.listenTo(this.model, 'change:isAlive', this.render)
            this.render()
        },
        render: function () {
            // Change the visual representation of aliveness
            if (this.model.get('isAlive')) {
                this.$el.addClass('alive')
            } else {
                this.$el.removeAttr('class')
            }
        },
        mouseover: function () {
            if(this.options.app.isPressing && !this.alreadyToggled) {
                this.model.toggle()
                this.alreadyToggled = true
            }
        },
        mouseout: function () {
            this.alreadyToggled = false
        },
        cellClicked: function () {
            this.model.toggle()
        }
    })

    Model = Backbone.Model.extend({
        defaults: {
            isAlive: false,
            willLive: null,
            x: null,
            y: null,
            size: null
        },
        initialize: function () {
            this.neighbors = [] //Yes, I know this isn't a model property. The push syntax is too cumbersome and I don't need the eventing on neighbors
        },
        /**
         * Given a grid of items, determine which items are adjacent to me.
         * Requires that this.x and this.y be set
         * @param grid a 2d array of models like this one
         */
        calculateNeighbors: function (grid) {
            var x = this.get('x'),
                y = this.get('y')

            //above
            this.setNeighbor(grid, x-1, y-1)
            this.setNeighbor(grid, x, y-1)
            this.setNeighbor(grid, x+1, y-1)
            //same level
            this.setNeighbor(grid, x-1, y)
            this.setNeighbor(grid, x+1, y)
            //below
            this.setNeighbor(grid, x-1, y+1)
            this.setNeighbor(grid, x, y+1)
            this.setNeighbor(grid, x+1, y+1)

            //console.log('['+ this.get('x') +']['+ this.get('y') +'] has '+ this.neighbors.length +' neighbors')
        },
        setNeighbor: function (grid, x, y) {
            if (!grid[x]) { return }
            var possibleNeighbor = grid[x][y]
            if (possibleNeighbor && possibleNeighbor instanceof Backbone.Model) {
                this.neighbors.push( possibleNeighbor )
            }
        },

        toggle: function () {
            this.set(
                'isAlive',
                !this.get('isAlive')
            )
        },
        kill: function () { this.set('willLive', false) },
        birth: function () { this.set('willLive', true) },
        randomize: function () {
            this.set('willLive', null)
            this.set('isAlive', !!(Math.round(Math.random() * 10) % 2) )
        },

        /**
         * Look at neighbors and determine if I should stay alive, stay dead, be born, or die
         */
        compete: function () {
            // Get the count of live neighbors
            var i, count = 0

            for (i=0; i < this.neighbors.length; i++) {
                if (this.neighbors[i].get('isAlive')) {
                    count++
                }
            }

            // If alive
            if (this.get('isAlive')) {
                switch (count) {
                    //Any live cell with fewer than two live neighbours dies, as if caused by under-population
                    case 0:
                    case 1:
                        this.kill()
                        break
                    //Any live cell with two or three live neighbours lives on to the next generation
                    case 2:
                    case 3:
                        this.set('willLive', this.get('isAlive'))
                        break //stays alive
                    //Any live cell with more than three live neighbours dies, as if by overcrowding
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                        this.kill()
                }

            // If dead
            } else {
                //Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
                if (count === 3) {
                    this.birth()
                }
            }
        },

        step: function() {
            this.set('isAlive', this.get('willLive'))
            this.set('willLive', null)
        }
    })
    // Publicize
    window.CellModel = Model
    window.CellView = View
})(window, _, Backbone)



// ----------------------------- The Application Object
;(function(window, undefined, $, _){
    var Application, _defaultMetabolism = 100

    Application = Backbone.View.extend({
        events:  {
            'touchstart': 'startPress',
            'mousedown': 'startPress',
            'mouseup': 'endPress',
            'touchend': 'endPress'
        },
        startPress: function() { this.isPressing = true },
        endPress: function() { this.isPressing = false },
        initialize: function() {
            _.bindAll(this, 'buildCells', 'toggleBtnClicked', 'cleanSlate', 'randomize', 'stop', 'start', 'live')
            this.columns = this.options.columns
            this.rows = this.options.rows
            this.cellSize = this.options.size
            this.paused = true
            this.setElement('#GameOfLife')
            this.buildCells()
            this.render()
            $('#Start').on('click', this.toggleBtnClicked)
            $('#Clear').on('click', this.cleanSlate)
            $('#Random').on('click', this.randomize)
        },
        buildCells: function () {
            //console.log("Building a grid with " + this.columns + " columns and "+ this.rows +" rows")
            var i, j, curModel, curView, cell2d = []
            this.cells = []

            // Build a new CellModel for every column & row
            for (i=0; i<this.rows; i++) {
                cell2d[i] = []
                for (j=0; j<this.columns; j++) {
                    curModel = new window.CellModel({ 'x': i, 'y': j, 'size': this.cellSize })
                    curView = new window.CellView({ model: curModel, app: this })
                    cell2d[i].push( curModel )
                    this.cells.push( curModel )
                    this.$el.append( curView.el )
                }
                this.$el.append('<br/>')
            }

            // Give each cell a reference to all its neighbors
            _.each(this.cells, function(cell){
                cell.calculateNeighbors(cell2d)
            }.bind(this))
        },

        toggleBtnClicked: function () {
            if (this.paused) {
                this.start()
            } else {
                this.stop()
            }
        },

        stop: function () {
            $('body').removeClass('running')
            this.paused = true
            $('#Start').text('Start')
        },
        start: function () {
            $('body').addClass('running')
            this.paused = false
            this.metabolism = $('#Metabolism').val() || _defaultMetabolism
            this.live()
            $('#Start').text('Stop')
        },

        live: function () {
            if (this.paused) { return }

            // Determine what to do in the next step
            _.each( this.cells, function(cell) { cell.compete() })
            // Live out the next step
            _.each( this.cells, function(cell) { cell.step() })
            // Keep on simulating life
            if (!this.paused) {
                setTimeout(this.live, this.metabolism)
            }
        },

        cleanSlate: function () {
            _.each( this.cells, function(cell) { cell.kill() })
            _.each( this.cells, function(cell) { cell.step() })
            this.stop()
        },

        randomize: function () {
            _.each( this.cells, function(cell) { cell.randomize() })
        }

    })

    // Publicize
    window.Application = Application
})(window, undefined, $, _)











// ----------------------------- Start the Game
;(function(window){

    console.clear() // Clean up the codepen output
    
    setTimeout(function(){
      // Determine game size by Screen size
      var gameOfLife,
        cellSize = 14,
        availWidth = window.innerWidth - 40,
        availHeight = window.innerHeight - 80,
        colCount = Math.floor( availWidth / cellSize ),
        rowCount = Math.floor( availHeight / cellSize )
      
      window.gameOfLife = new Application({
        columns: colCount,
        rows: rowCount,
        size: cellSize
      })
    }, 200) // Timeout needed because codepen doesn't have the full doc height drawn at document.ready time
})(window)

              
            
!
999px

Console