Skip to content

Instantly share code, notes, and snippets.

@marksim
Created May 14, 2013 03:26
Show Gist options
  • Save marksim/5573452 to your computer and use it in GitHub Desktop.
Save marksim/5573452 to your computer and use it in GitHub Desktop.
First pass at Conway's Game of Life implementation with @thecommongeek
require 'rspec'
class Life
def initialize
@cells = [
[Cell.new, Cell.new, Cell.new],
[Cell.new, Cell.new, Cell.new],
[Cell.new, Cell.new, Cell.new],
]
end
def make_alive(cell)
@cells[cell.y][cell.x] = cell
end
def lifecycle
@cells.each.with_index do |row, y|
row.each.with_index do |cell, x|
end
end
end
def live_cells
@cells.flatten.select(&:alive?)
end
end
class Cell
def initialize(options={})
@alive = options.fetch(:alive, false)
@x = options.fetch(:x, nil)
@y = options.fetch(:y, nil)
end
attr_accessor :number_of_neighbors, :x, :y
def alive?
@alive
end
def lifecycle
if number_of_neighbors < 2
@alive = false
elsif number_of_neighbors > 3
@alive = false
elsif number_of_neighbors == 3
@alive = true
end
end
def coords
[@x, @y]
end
end
describe Life do
describe "board" do
it "has many cells" do
game = Life.new
game.make_alive Cell.new(x: 0, y: 1, alive: true)
game.make_alive Cell.new(x: 1, y: 1, alive: true)
game.make_alive Cell.new(x: 2, y: 1, alive: true)
game.lifecycle
game.live_cells.map(&:coords).should include [1, 0]
game.live_cells.map(&:coords).should_not include [0, 1]
end
end
describe "live cells" do
let(:cell) { Cell.new(alive: true) }
it "dies if less than 2 live neighbors" do
cell.should be_alive
cell.number_of_neighbors = 1
cell.lifecycle
cell.should_not be_alive
end
it "dies if more than 3 neighbors, as if by overcrowding" do
cell.should be_alive
cell.number_of_neighbors = 4
cell.lifecycle
cell.should_not be_alive
end
it "lives if it has only 2 neighbors" do
cell.should be_alive
cell.number_of_neighbors = 2
cell.lifecycle
cell.should be_alive
end
it "lives if it has only 3 neighbors" do
cell.should be_alive
cell.number_of_neighbors = 3
cell.lifecycle
cell.should be_alive
end
end
describe "dead cells" do
it "becomes alive if exactly 3 live neighbors" do
cell = Cell.new(alive: false)
cell.should_not be_alive
cell.number_of_neighbors = 3
cell.lifecycle
cell.should be_alive
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment