lib/ep-codebreaker/game.rb in ep-codebreaker-0.3.2 vs lib/ep-codebreaker/game.rb in ep-codebreaker-0.4.0
- old
+ new
@@ -3,22 +3,26 @@
require_relative 'player'
require_relative 'game_writer'
module Codebreaker
class Game
- include GameWriter
-
MIN = 1
MAX = 6
LENGTH = 4
TRIES = 10
HINTS = 3
- private_constant :MIN, :MAX, :LENGTH, :TRIES, :HINTS
attr_reader :tries_left, :hints_left
+ private_constant :MIN, :MAX, :LENGTH, :TRIES, :HINTS
+
+ def initialize(writer = GameWriter.new, player_class = Player)
+ @writer = writer
+ @player_class = player_class
+ end
+
def start
@code = Array.new(LENGTH) { rand(MIN..MAX) }.join
@result = ''
@tries_left = TRIES
@hints_left = HINTS
@@ -49,15 +53,15 @@
def answer
@code if finished?
end
def save_score(name)
- write Player.new(name, @tries_left, @hints_left)
+ @writer.write @player_class.new(name, @tries_left, @hints_left)
end
def high_scores
- process_file
+ @writer.load_scores
end
def as_json
{
result: nil,
@@ -88,18 +92,17 @@
('+' * num_of_pluses) + ('-' * num_of_minuses)
end
def generate_hint
- hint = '_' * LENGTH
index = @indexes_for_hint.delete(@indexes_for_hint.sample)
- hint[index] = @code[index]
- hint
+ ('_' * LENGTH).tap { |hint| hint[index] = @code[index] }
end
def verify(input)
- regexp = Regexp.new("^[#{MIN}-#{MAX}]{#{LENGTH}}$")
- msg = "Guesses must consist of #{LENGTH} digits from #{MIN} to #{MAX}"
+ regexp = /\A[#{MIN}-#{MAX}]{#{LENGTH}}\z/
+ msg = "Guesses must consist of #{LENGTH} digits from #{MIN} to #{MAX}"
+
raise(ArgumentError, msg) if !input.is_a?(String) || !input.match?(regexp)
end
end
end