Sha256: 7b2a9e258053b917433c926e110bd44ae753a0f0ec85167b0ae66ef2e53c560c

Contents?: true

Size: 1.13 KB

Versions: 7

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require_relative 'autoload'
require_relative 'game'

class GuessHandler
  def respond_to_guess(game, input, code)
    validation(input)
    return game.give_a_hint if input == 'hint'

    @result = []
    @code_clone = code.clone
    @numbers = input.split('').map(&:to_i)
    return 'win' if @numbers == code

    assess_guess(@code_clone, @numbers)
    attempts_handler(game)
  end

  def assess_guess(code, input)
    @numbers.each_with_index do |element, index|
      if element == code[index]
        code[index] = '+'
        input[@numbers.index(element)] = '' end
    end

    @result = code.each_with_index do |el, index|
      if @numbers.include?(el)
        code[index] = '-'
        input.slice!(@numbers.index(el)) end
    end
  end

  def attempts_handler(game)
    game.user.attempts[:used] += 1
    if game.user.attempts[:used] >= game.user.attempts[:all]
      'loss'
    else
      @result.delete_if do |value|
        (1..6).include?(value)
      end.sort
    end
  end

  private

  def validation(input)
    Validations.validate_guess(input)
  rescue StandardError => e
    puts e.message
    nil
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
codebreaker_kirill-1.0.2 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-1.0.1 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-1.0.0 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-0.3.3 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-0.3.2 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-0.3.1 lib/codebreaker_kirill/guess_handler.rb
codebreaker_kirill-0.3.0 lib/codebreaker_kirill/guess_handler.rb