Skip to content

Instantly share code, notes, and snippets.

@tcrayford
Created March 10, 2011 20:23
Show Gist options
  • Save tcrayford/864852 to your computer and use it in GitHub Desktop.
Save tcrayford/864852 to your computer and use it in GitHub Desktop.
An (unfinished) game of life implementation by @t_crayford and @AvivBY
#Any live cell with fewer than two live neighbours dies, as if caused by under-population.
#Any live cell with two or three live neighbours lives on to the next generation.
#Any live cell with more than three live neighbours dies, as if by overcrowding.
#Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
class Cell
attr_accessor :x, :y
def initialize(x,y)
@x = x
@y = y
end
def neighbour_of?(other_cell)
close_by?(:x, other_cell) && close_by?(:y, other_cell)
end
def close_by?(direction, other_cell)
(other_cell.send(direction) - self.send(direction)).abs < 2
end
end
class Grid
def initialize(*cells)
@cells = cells
end
def alive_neighbours_around(cell)
@cells.select { |c| c.neighbour_of?(cell) }.size - 1
end
end
describe 'counting live neighbours' do
let(:center_cell) { Cell.new(0,0) }
it 'returns zero alive neighbours around a lonely cell' do
grid = Grid.new(center_cell)
grid.alive_neighbours_around(center_cell).should == 0
end
it 'alive_neighbours_around should probably be named something else'
it 'returns one alive neighbour around a cell with one neighbour' do
grid = Grid.new(Cell.new(1,0), center_cell)
grid.alive_neighbours_around(center_cell).should == 1
end
it 'returns one alive neighbour around a cell with one neighbour, and one distant cousin' do
grid = Grid.new(Cell.new(1,0), center_cell, Cell.new(100,100))
grid.alive_neighbours_around(center_cell).should == 1
end
it 'returns 0 for a far away northern cousin' do
grid = Grid.new(Cell.new(0,100), center_cell)
grid.alive_neighbours_around(center_cell).should == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment