Commit d8f8838

mo khan <mo@mokhan.ca>
2014-04-26 15:41:34
extract difficulty and allow it to generate a list of operands to compute.
1 parent f9eafab
Changed files (6)
bin/mathy.rb
@@ -9,4 +9,5 @@ operations = [
 
 console = Mathy::Console.new
 game = Mathy::Game.new(console)
-game.play(console.how_many_turns?, console.operation?(operations))
+difficulty = Mathy::Difficulties::GradeTwo.new
+game.play(console.how_many_turns?, console.operation?(operations), difficulty)
lib/mathy/difficulties/grade_two.rb
@@ -0,0 +1,9 @@
+module Mathy
+  module Difficulties
+    class GradeTwo
+      def next_operands
+        [rand(20), rand(10)]
+      end
+    end
+  end
+end
lib/mathy/operations/addition.rb
@@ -8,13 +8,21 @@ module Mathy
         @key = "+"
       end
 
-      def play_turn(x: rand(10), y: rand(20))
-        @verifier.check_answer("#{x} + #{y} = ", x + y)
+      def play_turn(operands)
+        @verifier.check_answer("#{operands.join(" + ")} = ", calculate(operands))
       end
 
       def matches?(other_key)
         key == other_key
       end
+
+      private
+
+      def calculate(operands)
+        operands.inject(0) do |result, x|
+          result + x
+        end
+      end
     end
   end
 end
lib/mathy/operations/subtraction.rb
@@ -8,8 +8,9 @@ module Mathy
         @key = "-"
       end
 
-      def play_turn(x: rand(10), y: rand(20))
-        @verifier.check_answer("#{x} - #{y} = ", x - y)
+      def play_turn(difficulty)
+        operands = difficulty.next_operands
+        @verifier.check_answer("#{operands.join(" - ")} = ", operands.inject() { |result, x| result - x })
       end
 
       def matches?(other_key)
lib/mathy/game.rb
@@ -5,9 +5,9 @@ module Mathy
       @score = score
     end
 
-    def play(games_to_play = 2, operation)
+    def play(games_to_play = 2, operation, difficulty)
       games_to_play.times do
-        @score += 1 if operation.play_turn
+        @score += 1 if operation.play_turn(difficulty.next_operands)
       end
 
       display_results(@name, @score, games_to_play)
lib/mathy.rb
@@ -5,5 +5,7 @@ require 'mathy/game'
 require 'mathy/operations/addition'
 require 'mathy/operations/subtraction'
 
+require 'mathy/difficulties/grade_two'
+
 module Mathy
 end