lib/ep-codebreaker/game.rb in ep-codebreaker-0.3.0 vs lib/ep-codebreaker/game.rb in ep-codebreaker-0.3.1
- old
+ new
@@ -1,9 +1,14 @@
# frozen_string_literal: true
+require_relative 'player'
+require_relative 'game_writer'
+
module Codebreaker
class Game
+ include GameWriter
+
MIN = 1
MAX = 6
LENGTH = 4
REGEXP = Regexp.new("^[#{MIN}-#{MAX}]{#{LENGTH}}$")
@@ -40,14 +45,11 @@
@tries_left -= 1
@hints_left -= 1
define_stage
- index = @indexes_for_hint.delete(@indexes_for_hint.sample)
- hint = '_' * LENGTH
- hint[index] = @code[index]
- hint
+ generate_hint
end
def finished?
@finished
end
@@ -58,22 +60,16 @@
def answer
@code if finished?
end
- def save_score(name, file_name = 'scores.yml')
- player = Player.new(name, @tries_left, @hints_left)
-
- scores = process_file(file_name)
- scores << player
- scores = scores.max_by(10, &:points)
-
- File.open(file_name, 'w') { |f| f.write scores.to_yaml }
+ def save_score(name)
+ write Player.new(name, @tries_left, @hints_left)
end
- def high_scores(file_name = 'scores.yml')
- process_file file_name
+ def high_scores
+ process_file
end
def as_json
{
result: nil,
@@ -103,21 +99,23 @@
num_of_minuses = LENGTH - num_of_pluses - code_chars.size
('+' * 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
+ end
+
def define_stage(result = '')
if result == ('+' * LENGTH)
@finished = true
@won = true
elsif @tries_left.zero?
@finished = true
end
- end
-
- def process_file(file_name)
- return [] if !File.exist?(file_name) || File.zero?(file_name)
- YAML.load_file(file_name)
end
def verify(input)
msg = "Guesses must consist of #{LENGTH} digits from #{MIN} to #{MAX}"
raise(ArgumentError, msg) if !input.is_a?(String) || !input.match?(REGEXP)