# frozen_string_literal: true module CodebreakerRuban class Game include Validation attr_reader :difficulty, :attempts_total, :hints_total, :user, :secret_code attr_accessor :attempts_used, :hints_used, :errors LENGTH_GUESS = 4 RANGE_SECRET_CODE = (1..6).freeze EASY = { hints_total: 2, attempts_total: 15, difficulty: 'easy' }.freeze MEDIUM = { hints_total: 1, attempts_total: 10, difficulty: 'medium' }.freeze HELL = { hints_total: 1, attempts_total: 5, difficulty: 'hell' }.freeze def initialize(difficulty, user) @user = user @difficulty = difficulty[:difficulty] @secret_code = generator_secret_code @attempts_total = difficulty[:attempts_total] @hints_total = difficulty[:hints_total] @hint = secret_code.clone.shuffle @hints_used = 0 @attempts_used = 0 @errors = [] end def validate_guess_input(input) clear_errors return errors << Message.error_guess_code unless validate_range_lenght(input, LENGTH_GUESS) return errors << Message.error_guess_code unless check_number(transform_in_array(input), RANGE_SECRET_CODE) end def check_attemps @attempts_used += 1 @attempts_used != @attempts_total end def check_user_input(input) input = transform_in_array(input) result = [] secret_arr = secret_code.clone user_arr = input.clone check_plus(user_arr, secret_arr, result).compact! check_minus(user_arr, secret_arr, result) [result].join('') end def hint_use if @hints_used < @hints_total @hints_used += 1 @hint.pop else clear_errors errors << Message.error_guess_code end end def to_h { name: @user.name.capitalize, difficulty: @difficulty, attempts_used: @attempts_used, attempts_total: @attempts_total, hints_total: @hints_total, hints_used: @hints_used } end private def check_plus(user_arr, secret_arr, plus) user_arr.each_index do |index| next unless user_arr[index] == secret_arr[index] plus << '+' user_arr[index] = nil secret_arr[index] = nil end end def check_minus(user_arr, secret_arr, minus) user_arr.each_with_index do |number, index| next unless secret_arr.include? number minus << '-' index_s = secret_arr.find_index number user_arr[index] = nil secret_arr[index_s] = nil end end def transform_in_array(arg) arg.split('').map(&:to_i) end def clear_errors errors.clear end def generator_secret_code Array.new(LENGTH_GUESS) { Random.rand(RANGE_SECRET_CODE) } end end end