Commit fc7a9f1
Changed files (5)
lib/cell.rb
@@ -0,0 +1,43 @@
+class Cell
+ attr_accessor :x, :y
+
+ def initialize(populated: false)
+ @populated = populated
+ end
+
+ def spawn(world)
+ populated_neighbors = world.neighbors_for(self).find_all { |x| x.populated? }
+ if populated?
+ Cell.new(populated: (2...4).include?(populated_neighbors.count))
+ else
+ Cell.new(populated: populated_neighbors.count == 3)
+ end
+ end
+
+ def neighbor?(other_cell)
+ if matches_x?(other_cell) && one_cell_away(other_cell.y - self.y)
+ return true
+ elsif matches_y?(other_cell) && one_cell_away(other_cell.x - self.x)
+ return true
+ end
+ false
+ end
+
+ def populated?
+ @populated
+ end
+
+ private
+
+ def matches_x?(other_cell)
+ other_cell.x == x
+ end
+
+ def matches_y?(other_cell)
+ other_cell.y == y
+ end
+
+ def one_cell_away(difference)
+ difference.abs == 1
+ end
+end
lib/world.rb
@@ -0,0 +1,15 @@
+class World
+ def initialize(cells)
+ @cells = cells
+ end
+
+ def neighbors_for(cell)
+ @cells.find_all { |x| cell.neighbor?(x) }
+ end
+
+ def begin
+ @cells.each do |cell|
+ cell.spawn(self)
+ end
+ end
+end
spec/cell_spec.rb
@@ -1,46 +1,3 @@
-class Cell
- attr_accessor :x, :y
- def initialize(populated: false)
- @populated = populated
- end
-
- def spawn(world)
- populated_neighbors = world.neighbors_for(self).find_all { |x| x.populated? }
- if populated?
- Cell.new(populated: (2...4).include?(populated_neighbors.count))
- else
- Cell.new(populated: populated_neighbors.count == 3)
- end
- end
-
- def neighbor?(other_cell)
- if matches_x?(other_cell) && one_cell_away(other_cell.y - self.y)
- return true
- elsif matches_y?(other_cell) && one_cell_away(other_cell.x - self.x)
- return true
- end
- false
- end
-
- def populated?
- @populated
- end
-
- private
-
- def matches_x?(other_cell)
- other_cell.x == x
- end
-
- def matches_y?(other_cell)
- other_cell.y == y
- end
-
- def one_cell_away(difference)
- difference.abs == 1
- end
-end
-
describe Cell do
let(:populated_neighbor) { Cell.new(populated: true) }
let(:unpopulated_neighbor) { Cell.new(populated: false) }
spec/spec_helper.rb
@@ -14,6 +14,8 @@
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
+require "world"
+require "cell"
RSpec.configure do |config|
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
spec/world_spec.rb
@@ -1,19 +1,3 @@
-class World
- def initialize(cells)
- @cells = cells
- end
-
- def neighbors_for(cell)
- @cells.find_all { |x| cell.neighbor?(x) }
- end
-
- def begin
- @cells.each do |cell|
- cell.spawn(self)
- end
- end
-end
-
describe World do
subject { World.new(cells) }
let(:cells) { [neighbor, other_cell] }