Sha256: afa3db61c3636822c7b2c0f1e6b1a4c31d59de7e83dd55dd03b0f78d257c5105

Contents?: true

Size: 1.51 KB

Versions: 2

Compression:

Stored size: 1.51 KB

Contents

# frozen_string_literal: true

class Game
  GUESS_PRESENCE = '-'
  GUESS_PLACE = '+'

  attr_reader :secret_code, :attempts_counter, :hinted_numbers, :current_difficulty, :win

  def initialize(difficulty)
    @secret_code = create_secret_code
    @guess = []
    @attempts_counter = 0
    difficulty(difficulty)
  end

  def difficulty(difficulty)
    @current_difficulty = difficulty.level
    @hinted_numbers = @secret_code.sample(@current_difficulty[:hints])
  end

  def check_number_match(guess)
    @guess = guess
    @attempts_counter += 1
    if @guess == @secret_code
      @win = true
      return win_string
    end

    number_match(exact_match)
  end

  def take_hint
    @hinted_numbers.pop
  end

  def win?(string)
    string == win_string
  end

  def lose?
    @attempts_counter >= @current_difficulty[:attempts]
  end

  private

  def win_string
    GUESS_PLACE * Guess::VALID_GUESS_LENGTH
  end

  def create_secret_code
    Array.new(4) { rand(0..6) }
  end

  def exact_match
    array = @secret_code.dup
    array.map.with_index do |_char, index|
      next unless array[index] == @guess[index]

      @guess[index] = nil
      GUESS_PLACE
    end.compact
  end

  def number_match(pluses)
    s_code = @secret_code.map.with_index { |char, index| @guess[index].nil? ? nil : char }.compact
    @guess.compact!
    s_code.map.with_index do |_char, index|
      if s_code.include? @guess[index]
        s_code[s_code.index(@guess[index])] = nil
        pluses << GUESS_PRESENCE
      end
    end
    pluses.join
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
codebreaker_gapdn-0.1.1 lib/codebreaker_gapdn/game.rb
codebreaker_gapdn-0.1.0 lib/codebreaker/game.rb