# frozen_string_literal: true class Console include Codebreaker COMMANDS = { start: 'start', rules: 'rules', stats: 'stats', exit: 'exit', hint: 'hint', yes: 'y', no: 'n', win: 'win' }.freeze def initialize @state = :choice_main end def run loop do send(@state) break if @state == :exit end end def welcome show :welcome end def goodbye show :goodbye end private def choice_main show(:menu) case input when COMMANDS[:start] then @state = :register_name when COMMANDS[:rules] then @state = :rules when COMMANDS[:stats] then @state = :output_stats when COMMANDS[:exit] then @state = :exit else show(:invalid_command) end end def register_name show(:name_request) name = input @player = Player.new(name) @player.validate ? @state = :register_difficulty : show(:invalid_name) end def register_difficulty show(:difficulty_request) difficult = input.downcase if Difficulties.valid_difficult(difficult) @difficult = Difficulties.new(difficult) @state = :create_game else show(:invalid_difficulty) end end def create_game @codebreaker = Game.new(@player, @difficult) @state = :game_process end def game_process return @state = :lose if @codebreaker.lose? show(:game_process) code = input return @state = :hint if hint?(code) return @state = :win if @codebreaker.win?(code) result = @codebreaker.check_code(code) return show(:invalid_code) if result.nil? puts result end def win show(:win_game_message) @state = :save_stats end def lose show(:lost_game_message, code: @codebreaker.number.join) @state = :choice_main end def hint @codebreaker.hints? ? show(:hint_message, hint: @codebreaker.hint) : show(:no_hints_message) @state = :game_process end def rules show(:rules) @state = :choice_main end def save_stats show(:save_result) if input == COMMANDS[:yes] Statistics.save(@codebreaker.to_h) @state = :choice_main elsif input == COMMANDS[:no] @state = :choice_main end end def output_stats puts Statistics.output @state = :choice_main end def hint?(code) code == COMMANDS[:hint] end def show(message, optional = {}) puts I18n.t(message, optional) end def input user_input = gets.chomp user_input.downcase == COMMANDS[:exit] ? @state = :exit : user_input end end