Sha256: bf70d442fe773dd713b261fc86d24ea034d99643551bbf353576df3701f39158

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module AndriiCodebreaker
  class Game
    include Statistic
    include Constant

    attr_reader :player_name, :difficulties, :secret_code
    attr_accessor :used_hints, :used_attempts, :available_hints

    CONST_COMMAND = {
      start: I18n.t('game.start'),
      rules: I18n.t('game.rules'),
      stats: I18n.t('game.stats'),
      exit: I18n.t('game.exit')
    }.freeze

    def initialize(player_name, difficulty)
      @player_name = User.new(player_name)
      @difficulties = Difficulty.new(difficulty)
      @used_attempts = 0
      @used_hints = 0
    end

    def start
      @secret_code = generate_code
      @available_hints = @secret_code.join.dup
    end

    def hint
      return unless left_hint?

      hint = @available_hints.chars.sample
      @available_hints.sub!(hint, '')
      @used_hints += 1
      hint
    end

    def left_hint?
      @used_hints < @difficulties.hints
    end

    def left_attempts?
      @used_attempts < @difficulties.attempts
    end

    def win?(guees)
      return true if @secret_code.join == guees

      false
    end

    def lose
      return false unless left_attempts?

      true
    end

    def compare_codes(guess)
      @used_attempts += 1

      guess = guess.chars.map(&:to_i)
      minuses = (@secret_code & guess).map { |element| [@secret_code.count(element), guess.count(element)].min }.sum
      result = MINUS * minuses

      check_result(result, guess)
    end

    def check_result(result, guess)
      guess.each.with_index do |code, index|
        result.sub!(MINUS, PLUS) if code == @secret_code[index]
      end
      result
    end

    def generate_code
      Array.new(CODE_LENGTH_COUNT) { rand(RANGE_SECRET_CODE) }
    end

    def code_valid?(code)
      code.to_s.match(/^[1-6]{4}$/)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
andrii_codebreaker-0.1.10 lib/andrii_codebreaker/game.rb