Skip to content

Instantly share code, notes, and snippets.

@zorbash
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save zorbash/4a8d3247fc14f2ee9958 to your computer and use it in GitHub Desktop.

Select an option

Save zorbash/4a8d3247fc14f2ee9958 to your computer and use it in GitHub Desktop.
class app.Views.Automaton
defaults =
interval: 100
(@$cells, options) ->
@options = $.extend {}, defaults, options
@_bindHandlers!
step: (gen = 0) ~>
@$cells.each (_, cell) ~>
(($cell) ~>
@survival $cell,
-> $cell.removeClass('dead'),
-> $cell.addClass('dead'))($(cell))
setTimeout((~> @step(gen + 1)), @options.interval)
survival: ($cell, life, death) ~>
((is-alive) ~>
return life! if @_lives(is-alive, $cell)
return death! if @_dies is-alive, $cell)(@_is-alive($cell))
_is-alive: ($cell) -> !$cell.hasClass('dead')
_lives: (is-alive, $cell) ~>
(!is-alive && @_reproduction $cell) || (is-alive && @_stagnation $cell)
_dies: (is-alive, $cell) ~>
(is-alive && @_under-population $cell) || (is-alive && @_overcrowding $cell)
_under-population: ($cell) -> @_neighbors($cell).length < 2
_stagnation: ($cell) -> @_neighbors($cell).length in [2, 3]
_overcrowding: ($cell) -> @_neighbors($cell).length > 3
_reproduction: ($cell) -> @_neighbors($cell).length == 3
_neighbors: ($cell) ~>
[@_nw, @_n, @_ne, @_e, @_s, @_se, @_sw, @_w]
|> _.map _, (dir) -> dir($cell)
|> _.compact
|> _.filter _, ($neib) -> !$neib.hasClass(\dead)
|> _.reduce _, (($acc, $neib) -> $acc.add $neib), $!
_nw: ($cell) ~>
return null if @_row($cell) == 0 || @_col($cell) == 0
@$cells.eq $cell.index! - (@options.dimensions.n + 1)
_n: ($cell) ~>
return null if @_row($cell) == 0
@$cells.eq $cell.index! - @options.dimensions.n
_ne: ($cell) ~>
return null if @_row($cell) == 0 || (@_col($cell) == @options.dimensions.n - 1)
@$cells.eq $cell.index! - (@options.dimensions.n - 1)
_sw: ($cell) ~>
return null if @_row($cell) == (@options.dimensions.m - 1) || (@_col($cell) == 0)
@$cells.eq $cell.index! + (@options.dimensions.n - 1)
_w: ($cell) ~>
return null if @_col($cell) == 0
@$cells.eq $cell.index! - 1
_e: ($cell) ~>
return null if @_col($cell) == @options.dimensions.n - 1
@$cells.eq $cell.index! + 1
_s: ($cell) ~>
return null if @_col($cell) == @options.dimensions.m - 1
@$cells.eq $cell.index! + @options.dimensions.n
_se: ($cell) ~>
return null if (@_row($cell) == @options.dimensions.m - 1) ||
(@_col($cell) == @options.dimensions.n - 1)
@$cells.eq $cell.index! + (@options.dimensions.n + 1)
_row: ($cell) ~> ~~($cell.index! / @options.dimensions.n)
_col: ($cell) ~> $cell.index! - (@_row($cell) * @options.dimensions.n)
_bindHandlers: ~>
@$cells.last!.on \click, ~>
@$cells.filter('[data-bw=white]').addClass \dead
@step!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment