require 'json' require_relative 'codebreaker_first/version' module CodebreakerFirst MAX_TRIES = 6 # Rubocop class Game attr_accessor :code, :user_tries, :game_result def initialize(code = '', user_tries = 0, game_result = nil) @code = code @user_tries = user_tries @game_result = game_result end def from_hash(data) Game.new data['code'], data['user_tries'], data['game_result'] end def start return if code.length 4.times do @code << rand(1...6).to_s end end def check_code(input_code) @user_tries += 1 return lose if @user_tries >= MAX_TRIES return win if input_code == @code validate_code input_code result = '' @code.chars.each.with_index do |char, index| case char == input_code[index] when true result << '+' else result << '-' if input_code.include? char end end result end def win @game_result = true end def lose @game_result = false end def save_result(name) raise Exception, 'To save, you must finish the game!' if @game_result.nil? Result.save name, @user_tries, @game_result end def results Result.results end private def validate_code(code) raise Exception unless code.is_a?(Numeric) || code.is_a?(String) code = code.to_s raise Exception, 'Code must contains 4 numbers from 1 to 6' unless code =~ /^[1-6]{4}$/ end end # Rubocop class Result SCORES_FILE = File.expand_path('scores.json', __dir__) def self.save(name, tries, result) scores = results.to_a scores << { name: name, tries: tries, result: result } File.write SCORES_FILE, scores.to_json scores end def self.results file = File.read SCORES_FILE JSON.parse file end end end