module Codebreaker class Game ATTEMPTS_COUNT = 10 HINTS_COUNT = 3 attr_reader :attempt, :hint, :is_winner def initialize @secret_code = generate_code @attempt = 0 @hint = 0 @is_winner = false end def attempts_left ATTEMPTS_COUNT - @attempt end def hints_left HINTS_COUNT - @hint end def generate_code @secret_code = Array.new(4){ rand(6) + 1 }.join end def guess(input) return if input.length != 4 @attempt += 1 secret = @secret_code.chars.map(&:to_i) result = [] input.chars.map(&:to_i).each_with_index do |digit, index| if digit == secret[index] secret[index] = nil result << '+' elsif secret.include? digit secret[secret.find_index(digit)] = nil result << '-' end end normalized_output = result.sort.join @is_winner = true if normalized_output == '++++' normalized_output end def hint return unless HINTS_COUNT > @hint @hint += 1 @secret_code[rand(4)] end def winner? @is_winner end def ended? ATTEMPTS_COUNT == @attempt || @is_winner end def save YAML::Store.new('storage/storage.yml').transaction do |storage| storage[Time.now] = "attempts taken: #{@attempt}; hints used: #{@hint}; result: #{(winner? ? 'won' : 'loose')}" end end end end