Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created December 14, 2011 02:47
Show Gist options
  • Save brianstorti/1475025 to your computer and use it in GitHub Desktop.
Save brianstorti/1475025 to your computer and use it in GitHub Desktop.
game of life
require "rspec"
class Cell
attr_accessor :world, :x, :y
def initialize(world, x=0, y=0)
@world, @x, @y = world, x, y
world.cells << self
end
def neighbors
@neighbors = []
@world.cells.each do |cell|
# Has a cell to the north
if self.x == cell.x and self.y == cell.y - 1
@neighbors << cell
end
# Has a cell to the north east
if self.x == cell.x - 1 and self.y == cell.y - 1
@neighbors << cell
end
# Has a cell to the left
if self.x == cell.x + 1 and self.y == cell.y
@neighbors << cell
end
# Has a cell to the right
if self.x == cell.x - 1 and self.y == cell.y
@neighbors << cell
end
end
@neighbors
end
def spawn_at(x, y)
Cell.new(world, x, y)
end
def die!
world.cells -= [self]
end
def dead?
!alive?
end
def alive?
world.cells.include?(self)
end
end
class World
attr_accessor :cells
def initialize
@cells = []
end
def tick!
cells.each do |cell|
if cell.neighbors.count < 2
cell.die!
end
end
end
end
describe "game of life" do
let(:world) { World.new }
context "cell utility methods" do
subject { Cell.new(world) }
it "spawn relative to" do
cell = subject.spawn_at(3, 5)
cell.is_a?(Cell).should be_true
cell.x.should == 3
cell.y.should == 5
cell.world.should == subject.world
end
it "detects a neighbor to the north" do
cell = subject.spawn_at(0, 1)
subject.neighbors.count.should == 1
end
it "detects a neigbor to the north east" do
cell = subject.spawn_at(1, 1)
subject.neighbors.count.should == 1
end
it "detects a neighbor to the left" do
cell = subject.spawn_at(-1, 0)
subject.neighbors.count.should == 1
end
it "detects a neighbor to the right" do
cell = subject.spawn_at(1, 0)
subject.neighbors.count.should == 1
end
it "dies" do
subject.die!
subject.world.cells.should_not include(subject)
end
end
it "Rule #1: Any live cell with fewer than two live neighbours dies, as if caused by under-population." do
cell = Cell.new(world)
new_cell = cell.spawn_at(2, 0)
world.tick!
cell.should be_dead
cell.neighbors.count.should == 0
end
it "Rule #2: Any live cell with two or three live neighbours lives on to the next generation." do
cell = Cell.new(world)
new_cell = cell.spawn_at(1, 0)
other_new_cell = cell.spawn_at(-1, 0)
world.tick!
cell.should be_alive
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment