Commit 847b0a2

mo khan <mo@mokhan.ca>
2014-06-23 03:11:28
extract printer class.
1 parent 3fa92b2
bin/gol
@@ -2,5 +2,6 @@
 $:.unshift('lib')
 require 'gol'
 
-game = Game.new($stdout)
-game.play(3, 3)
+max_x = 3
+max_y = 3
+Game.new(Printer.new(max_x)).play(max_x, max_y)
lib/gol/cell.rb
@@ -24,10 +24,6 @@ class Cell
     false
   end
 
-  def print
-    populated? ? "X" : " "
-  end
-
   def populated?
     @populated
   end
lib/gol/game.rb
@@ -6,8 +6,8 @@ class Game
   def play(max_x, max_y)
     world = World.new(create_cells(max_x, max_y))
     until world.empty? do
-      print(world, max_x)
-      world.next_generation
+      @printer.print(world)
+      world.next_generation!
     end
   end
 
@@ -23,13 +23,6 @@ class Game
 
   private
 
-  def print(world, max_x)
-    world.each_with_index do |cell, index|
-      @printer.print("#{cell.print}")
-      @printer.puts if (index+1) % max_x == 0
-    end
-  end
-
   def random_population
     rand(100).even?
   end
lib/gol/printer.rb
@@ -0,0 +1,12 @@
+class Printer
+  def initialize(max_x)
+    @max_x = max_x
+  end
+
+  def print(world)
+    world.each_with_index do |cell, index|
+      print cell.populated? ? "X" : " "
+      puts if (index+1) % @max_x == 0
+    end
+  end
+end
lib/gol/world.rb
@@ -9,7 +9,7 @@ class World
     @cells.find_all { |x| cell.neighbor?(x) }
   end
 
-  def next_generation
+  def next_generation!
     @cells = map { |cell| cell.spawn(self) }
   end
 
lib/gol.rb
@@ -1,3 +1,4 @@
 require "gol/cell"
 require "gol/game"
 require "gol/world"
+require "gol/printer"
spec/lib/game_spec.rb
@@ -2,12 +2,6 @@ describe Game do
   subject { Game.new(printer) }
   let(:printer) { double }
 
-  context "#start" do
-    it "prints the output of the world" do
-      expect(subject.play(3, 3)).to eql(new_world)
-    end
-  end
-
   context "#create_cells" do
     context "for a 2x2 grid" do
       let(:results) { subject.create_cells(2, 2) }
spec/lib/world_spec.rb
@@ -21,12 +21,12 @@ describe World do
     end
   end
 
-  context "#next_generation" do
+  context "#next_generation!" do
     subject { World.new([cell]) }
     let(:cell) { double(spawn: true) }
 
     it "visits each cell" do
-      subject.next_generation
+      subject.next_generation!
       expect(cell).to have_received(:spawn).with(subject)
     end
   end