Skip to content

Instantly share code, notes, and snippets.

@gmarik
Created May 14, 2011 21:31
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 gmarik/972658 to your computer and use it in GitHub Desktop.
Save gmarik/972658 to your computer and use it in GitHub Desktop.
coderetreat wpg
class Cell
end
class World
def initialize
@x = 50
@y = 50
end
def set(x, y, cell = Cell.new)
cell(x, y, cell)
self
end
def cell(x, y, cell = Cell.new)
@grid[x][y] = cell unless at(x,y)
end
def at(x,y)
@grid ||= {}
@grid[x] ||= {}
@grid[x][y]
end
def neighbours(x,y)
[
at(x - 1, y - 1),
at(x - 1, y ),
at(x - 1, y + 1),
at(x , y - 1),
at(x , y + 1),
at(x + 1, y - 1),
at(x + 1, y ),
at(x + 1, y + 1),
].compact
end
def next
w = World.new
@grid.each do |x, h|
@h.each do |y, c|
if cell = at(x,y)
case neighbours(x,y).size
when 2..3: w.cell(x,y, cell)
else
# do nothing
end
else
case neighbours(x,y).size
when 3: w.cell(x,y, Cell.new)
else
# do nothing
end
end
end
end
w
end
def to_s
col = []
@x.times do |x|
row = []
@y.times do |y|
row += [at(x,y) ? '#':'.', ' ']
end
col << row.join()
end
col
end
end
# 0 1 2
#
# 1 1 0
# 1 0 0
# 0 0 0
#
# 1 1 0
# 1 1 0
# 0 0 0
#
if $0 == __FILE__
world = World.new.
set(0,2).
set(1,2).
set(2,2).
set(1,0).
set(2,1).
set(10 + 0,2).
set(10 + 1,2).
set(10 + 2,2).
set(10 + 1,0).
set(10 + 2,1).
set(30,30).
set(30,31).
set(30,32)
loop do
print "\e[2J\e[f"
puts world.to_s
world = world.next
end
else
describe "World" do
it 'should have cell' do
world = World.new
cell = world.cell(1,2)
world.at(1,2).should == cell
end
it 'shoudl have no neighbours' do
world = World.new
cell = world.cell(1,2)
world.neighbours(1,2).should == []
end
it 'shoudl have neighbours' do
world = World.new
cell = world.cell(1,2)
neigbour = world.cell(1,1)
world.neighbours(1,2).should == [neigbour]
end
end
describe "Evolution" do
before :each do
@world = World.new
@world.cell(0,0)
@world.cell(0,1)
@world.cell(1,0)
end
it 'should spawn' do
world = @world.next
world.at(1,1).should be_a(Cell)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment