class Codebreaker::Game

Constants

DIFFICULTY

Attributes

attempts[R]
difficulty[R]
errors[R]
hint_keeper[R]
hints[R]
name[R]
play[R]
player[R]
result[R]
secret_code[R]
storage[R]

Public Class Methods

new() click to toggle source
# File lib/codebreaker/game.rb, line 16
def initialize
  @secret_code = 4.times.map { Random.rand(1..6) }
  @errors = []
end

Public Instance Methods

data_to_save(name) click to toggle source
# File lib/codebreaker/game.rb, line 46
def data_to_save(name)
  {
    name: name,
    difficulty: difficulty[:mode],
    attempts_total: difficulty[:attempts],
    attempts_used: difficulty[:attempts] - attempts,
    hints_total: difficulty[:hint],
    hints_used: difficulty[:hint] - hint_keeper.size
  }
end
guess(guess) click to toggle source
# File lib/codebreaker/game.rb, line 61
def guess(guess)
  '+' * exact_match_count(guess) + '-' * number_match_count(guess)
end
lost?() click to toggle source
# File lib/codebreaker/game.rb, line 38
def lost?
  attempts.zero?
end
set(user_input) click to toggle source
# File lib/codebreaker/game.rb, line 21
def set(user_input)
  return unless DIFFICULTY.key?(user_input.to_sym)

  @difficulty = DIFFICULTY.dig(user_input.to_sym)
  @hints = @difficulty.dig(:hint)
  @attempts = @difficulty.dig(:attempts)
  @hint_keeper = @secret_code.sample(hints)
end
take_hint!() click to toggle source
# File lib/codebreaker/game.rb, line 30
def take_hint!
  hint_keeper.pop
end
to_yaml(name) click to toggle source
# File lib/codebreaker/game.rb, line 42
def to_yaml(name)
  data_to_save(name)
end
use_attempt!() click to toggle source
# File lib/codebreaker/game.rb, line 57
def use_attempt!
  @attempts -= 1
end
won?(guess) click to toggle source
# File lib/codebreaker/game.rb, line 34
def won?(guess)
  secret_code.join == guess
end

Private Instance Methods

delete_first(code, num) click to toggle source
# File lib/codebreaker/game.rb, line 84
def delete_first(code, num)
  code.delete_at(code.index(num)) if code.index(num)
end
exact_match?(guess, index) click to toggle source
# File lib/codebreaker/game.rb, line 88
def exact_match?(guess, index)
  guess[index] == @secret_code[index]
end
exact_match_count(guess) click to toggle source
# File lib/codebreaker/game.rb, line 67
def exact_match_count(guess)
  (0..3).inject(0) do |count, index|
    count + (exact_match?(guess, index) ? 1 : 0)
  end
end
number_match_count(guess) click to toggle source
# File lib/codebreaker/game.rb, line 73
def number_match_count(guess)
  total_match_count(guess) - exact_match_count(guess)
end
total_match_count(guess) click to toggle source
# File lib/codebreaker/game.rb, line 77
def total_match_count(guess)
  secret = @secret_code.dup
  guess.inject(0) do |count, num|
    count + (delete_first(secret, num) ? 1 : 0)
  end
end