class CodebreakerDiz::Game

Attributes

errors[R]
hints_count[R]
tries_count[R]

Public Class Methods

new(difficulty: :kid) click to toggle source
# File lib/codebreaker_diz/game.rb, line 9
def initialize(difficulty: :kid)
  validate_difficulty(difficulty)

  @difficulty   = difficulty

  @hint_indexes = (0...CODE_LENGTH).to_a

  @secret       = Array.new(CODE_LENGTH) { rand(MIN_CODE_NUMBER..MAX_CODE_NUMBER) }

  @tries_count  = DIFFICULTIES[@difficulty][:tries]
  @hints_count  = DIFFICULTIES[@difficulty][:hints]

  @errors       = []
  @hints        = []

  @matches      = ''
end

Public Instance Methods

check_guess(input) click to toggle source
# File lib/codebreaker_diz/game.rb, line 27
def check_guess(input)
  input = to_array(input)

  return add_error(GuessFormatError) unless valid? input

  @tries_count -= 1

  resolver = CodeResolver.new(@secret, input)

  @matches = resolver.matches
end
data() click to toggle source
# File lib/codebreaker_diz/game.rb, line 61
def data
  {
    difficulty: DIFFICULTIES.keys.index(@difficulty),
    secret: @secret,
    tries_total: DIFFICULTIES[@difficulty][:tries],
    hints_total: DIFFICULTIES[@difficulty][:hints],
    tries_used: DIFFICULTIES[@difficulty][:tries] - @tries_count,
    hints_used: DIFFICULTIES[@difficulty][:hints] - @hints_count
  }
end
generate_hint() click to toggle source
# File lib/codebreaker_diz/game.rb, line 39
def generate_hint
  return add_error(NoHintsError) if @hints_count.zero?

  index = @hint_indexes.sample

  hint = @secret[index]

  @hint_indexes.delete index

  @hints_count -= 1

  @hints << hint
end
lose?() click to toggle source
# File lib/codebreaker_diz/game.rb, line 57
def lose?
  @tries_count.zero?
end
win?() click to toggle source
# File lib/codebreaker_diz/game.rb, line 53
def win?
  @matches == Array.new(CODE_LENGTH, EXACT_MATCH_SIGN).join
end

Private Instance Methods

add_error(err) click to toggle source
# File lib/codebreaker_diz/game.rb, line 74
def add_error(err)
  (@errors << err) && nil
end
to_array(input) click to toggle source
# File lib/codebreaker_diz/game.rb, line 82
def to_array(input)
  input.to_i.digits.reverse
end
valid?(input) click to toggle source
# File lib/codebreaker_diz/game.rb, line 86
def valid?(input)
  input.size == CODE_LENGTH && input.all? { |number| number.between? MIN_CODE_NUMBER, MAX_CODE_NUMBER }
end
validate_difficulty(difficulty) click to toggle source
# File lib/codebreaker_diz/game.rb, line 78
def validate_difficulty(difficulty)
  raise DifficultyError unless DIFFICULTIES.include? difficulty.to_sym
end