# frozen_string_literal: true module Codebreakergem class Game include Checker DIGIT_NUMBER = 4 CORRECT_PLACE_SYMBOL = '+' INCORRECT_PLACE_SYMBOL = '-' FILE = File.expand_path(__dir__ + '/../data/data.yml') PERMITTED_CLASSES = [Codebreakergem::User, Codebreakergem::Game, Codebreakergem::Easy, Codebreakergem::Hell, Codebreakergem::Medium, Symbol].freeze attr_reader :secret_code, :user attr_accessor :difficulty, :statistics def initialize(user, difficulty_title) @user = user @difficulty = difficulty_factory(difficulty_title) @secret_code = generate_code end def show_hint return I18n.t(:no_hints) unless difficulty.hints.positive? difficulty.hints -= 1 secret_code[difficulty.hints] end def try_guess(guess) if guess == secret_code save difficulty.attempts = 0 return I18n.t(:victory_message) end difficulty.attempts -= 1 return I18n.t(:out_of_attempts) unless difficulty.attempts.positive? make_guess(guess) end def save FileWorker.add_to_file(FILE, to_h) end def to_h source = difficulty_factory(difficulty.title) formater(source, source.attempts - difficulty.attempts, source.hints - difficulty.hints) end private def formater(source_difficulty, attempts_used, hints_used) { name: user.name, difficulty: difficulty.title, order: difficulty.order, attempts_total: source_difficulty.attempts, attempts_used: attempts_used, hints_total: source_difficulty.hints, hints_used: hints_used, game_time: Time.now.strftime('%Y.%m.%d - %H:%M:%S') } end def generate_code DIGIT_NUMBER.times.map { rand(1..6) }.join end def find_place(guess, code) result = '' (0...guess.length).each do |index| next unless guess[index] == code[index] result += CORRECT_PLACE_SYMBOL code[index] = ' ' guess[index] = '_' end result end def find_presence(guess, code) result = '' (0...guess.length).each do |index| position = code.index(guess[index]) if position result += INCORRECT_PLACE_SYMBOL code[position] = ' ' end end result end def make_guess(guess) code_copy = secret_code.dup find_place(guess, code_copy) + find_presence(guess, code_copy) end def difficulty_factory(difficulty_title) case difficulty_title when 'Easy' then Easy.new when 'Medium' then Medium.new when 'Hell' then Hell.new end end end end