Sha256: 8bc35438dc962792a62239a0160a9b4166b99fd09035329f0579d64e66b0468b

Contents?: true

Size: 1.52 KB

Versions: 1

Compression:

Stored size: 1.52 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, difficulties)
      @player_name = player
      @difficulties = difficulties
      @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 win?(guees)
      return true if @secret_code.join == guees

      false
    end

    def lose
      return false if @used_attempts < @difficulties.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.14 lib/andrii_codebreaker/game.rb