Skip to content

Instantly share code, notes, and snippets.

@wybo
Last active May 1, 2017 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wybo/d10d06e31f41874b982c to your computer and use it in GitHub Desktop.
Save wybo/d10d06e31f41874b982c to your computer and use it in GitHub Desktop.
Life
# AgentBase is Free Software, available under GPL v3 or any later version.
# Original AgentScript code @ 2013, 2014 Owen Densmore and RedfishGroup LLC.
# AgentBase (c) 2014, Wybo Wiersma.
# Life provides an implementation of Conway's Game of Life with a twist.
# This example demonstrates running multiple models on the same page.
u = ABM.util
class ABM.LifeModel extends ABM.Model
startup: ->
@livingColor = u.color.white
@deadColor = u.color.black
setup: ->
for patch in @patches.create()
if Math.random() < 0.3
@birth(patch)
else
@death(patch)
step: ->
# Alternate between updating each patch's living neighbor count,
# and changing the `living` state variable of each patch.
# Since both models are triggered by a requestAnimationFrame callback
# in an ABM.Animator, the models should be guaranteed to run in
# lock-step.
if @animator.ticks % 2 is 1
@countLivingNeighbors()
else
@enactBirthsAndDeaths()
countLivingNeighbors: () ->
for patch in @patches
if @linkEnabled
# If the models are "linked", a patch's neighbors exist
# only in the model to which it is linked.
linkedPatch = @linkedModel.patches.patch(patch.position)
else
linkedPatch = patch
patch.liveNeighbors = linkedPatch.neighbors().with((patch) ->
patch.living).length
enactBirthsAndDeaths: () ->
for patch in @patches
# A patch will go from being dead to being alive
# if it has exactly three living neighbors
if patch.liveNeighbors is 3
@birth(patch)
else
# A living patch will stay living only if it
# has exactly two living neighbors
unless patch.liveNeighbors is 2
@death(patch)
birth: (patch) ->
patch.living = true
patch.color = @livingColor
death: (patch) ->
patch.living = false
patch.color = @deadColor
linkModel: (model) ->
@linkedModel = model
@linkEnabled = true
setupBothModels: () ->
@setup()
@linkedModel.setup()
# Model definition done
options = {
patchSize: 8,
mapSize: 50
}
options.div = 'world2'
model1 = window.model1 = new ABM.LifeModel(options)
options.div = 'world1'
model2 = window.model2 = new ABM.LifeModel(options)
# make the model divs display side by side
model1.div.style.display = model2.div.style.display = 'inline-block'
model1.linkModel(model2)
model2.linkModel(model1)
model1.start()
model2.start()
# Uses the AgentBase library (03-02-2017 release)
# https://github.com/wybo/agentbase/commit/3501302567c018da82601cd858be2ea6d0b9c74d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment