Sha256: 1e70aeb836b0f10ba52df68fdd48548ed6732f8ad7a7ae3bc9ed0e986f36b0e8

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 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

    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 true if left_attempts?

      false
    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.12 lib/andrii_codebreaker/game.rb