Skip to content

Instantly share code, notes, and snippets.

@msuarz
Created December 2, 2011 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msuarz/1423354 to your computer and use it in GitHub Desktop.
Save msuarz/1423354 to your computer and use it in GitHub Desktop.
Conway's Game of Life in Coffeescript
class exports.GameOfLife
constructor: (@cells) -> @read_board()
evolve: ->
for row in [0...@size]
for col in [0...@size]
@evolve_at row, col
evolve_at: (@row, @col, neighbors = @neighbors()) ->
@die() unless 1 < neighbors < 4
@live() if neighbors is 3
die: -> @cells[@index()] = 0
live: -> @cells[@index()] = 1
index: -> @row * @size + @col
is_alive: (x, y) -> @board[x]?[y]
neighbors: -> (1 for [x, y] in @vicinity() when @is_alive x, y).length
vicinity: ->
[@row + x, @col + y] for [x, y] in [
[-1, -1], [0, -1], [1, -1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1]
]
read_board: ->
@size = Math.sqrt @cells.length
@board = (@cells[(x - 1) * @size...x * @size] for x in [1..@size])
{ GameOfLife } = require 'game_of_life'
should = require 'should'
describe "Conway's Game of Life", ->
game = (cells) -> @game = new GameOfLife cells
evolve = (cells) -> game(cells).evolve()
should_become = (expected_cells) -> @game.cells.should.eql expected_cells
describe 'Any live cell with fewer than two live neighbours dies,
as if caused by under-population', ->
it 'dies of loneliness', ->
evolve [
0, 0, 0,
0, 1, 0,
0, 0, 0,
]
should_become [
0, 0, 0,
0, 0, 0,
0, 0, 0,
]
it 'dies if isolated pair', ->
evolve [
1, 0, 0,
0, 1, 0,
0, 0, 0,
]
should_become [
0, 0, 0,
0, 0, 0,
0, 0, 0,
]
describe 'Any live cell with two or three live neighbours
lives on to the next generation', ->
it 'survives in cluster', ->
evolve [
1, 1, 0,
1, 1, 0,
0, 0, 0,
]
should_become [
1, 1, 0,
1, 1, 0,
0, 0, 0,
]
it 'survives as rect angle', ->
evolve [
1, 0, 0,
1, 0, 0,
1, 1, 1,
]
should_become [
0, 0, 0,
1, 0, 0,
1, 1, 0,
]
describe 'Any live cell with more than three live neighbours dies,
as if by overcrowding', ->
it 'kills all but the corners', ->
evolve [
1, 1, 1,
1, 1, 1,
1, 1, 1,
]
should_become [
1, 0, 1,
0, 0, 0,
1, 0, 1,
]
describe 'Any dead cell with exactly three live neighbours becomes a live cell,
as if by reproduction.', ->
it 'reproduces in a triangle', ->
evolve [
1, 0, 1,
0, 0, 0,
0, 1, 0,
]
should_become [
0, 0, 0,
0, 1, 0,
0, 0, 0,
]
it 'goes from X to diamond', ->
evolve [
1, 0, 1,
0, 1, 0,
1, 0, 1,
]
should_become [
0, 1, 0,
1, 0, 1,
0, 1, 0,
]
@showell
Copy link

showell commented Dec 2, 2011

Very nice, I like how clear the tests are. FWIW you might find my version interesting: http://shpaml.webfactional.com/misc/Game-Of-Life/docs/game.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment