lib/ep-codebreaker/game.rb in ep-codebreaker-0.1.2 vs lib/ep-codebreaker/game.rb in ep-codebreaker-0.2.0
- old
+ new
@@ -1,15 +1,28 @@
# frozen_string_literal: true
module Codebreaker
class Game
- attr_reader :tries_left
+ MIN = 1
+ MAX = 6
+ LENGTH = 4
+ REGEXP = Regexp.new("^[#{MIN}-#{MAX}]{#{LENGTH}}$")
+
+ TRIES = 10
+ HINTS = 3
+
+ private_constant :MIN, :MAX, :LENGTH, :REGEXP, :TRIES, :HINTS
+ attr_reader :tries_left, :hints_left
+
def start
@code = Array.new(LENGTH) { rand(MIN..MAX) }.join
- @hint = @code.chars.sample
+ @array_for_hints = @code.chars
+
@tries_left = TRIES
+ @hints_left = HINTS
+
@finished = false
@won = false
end
def check_guess(input)
@@ -20,36 +33,39 @@
result = check_input(@code.chars, input.chars)
define_stage result
result
end
- def use_hint
- @hint
+ def hint
+ return false if @hints_left.zero?
+
+ @tries_left -= 1
+ @hints_left -= 1
+ define_stage
+
+ index = rand(@array_for_hints.length)
+ @array_for_hints.delete_at(index)
end
def finished?
@finished
end
def won?
@won
end
- def tries
- TRIES - @tries_left
- end
-
def answer
@code if finished?
end
def save_score(name, file_name = 'scores.yml')
- player = Player.new(name, tries)
+ player = Player.new(name, @tries_left, @hints_left)
scores = process_file(file_name)
scores << player
- scores = scores.min_by(10, &:tries)
+ scores = scores.max_by(10, &:points)
File.open(file_name, 'w') { |f| f.write scores.to_yaml }
end
def high_scores(file_name = 'scores.yml')
@@ -69,10 +85,10 @@
num_of_minuses = LENGTH - num_of_pluses - code_chars.size
('+' * num_of_pluses) + ('-' * num_of_minuses)
end
- def define_stage(result)
+ def define_stage(result = '')
if result == ('+' * LENGTH)
@finished = true
@won = true
elsif @tries_left.zero?
@finished = true