class CodeBreaker

Constants

LEVEL

Attributes

attempts[R]
difficulty[R]
hints[R]
name[R]

Public Class Methods

new(name, chose_level) click to toggle source
# File lib/codebreaker/codebreaker.rb, line 21
def initialize(name, chose_level)
  @codemaker = CodeMaker.new
  @attempts = LEVEL.dig(chose_level, :attempts)
  @hints = LEVEL.dig(chose_level, :hints)
  @difficulty = LEVEL.dig(chose_level, :difficulty)
  @name = registration(name)
  @hint_cache = []
end
stats() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 17
def self.stats
  CodeBreaker.load || []
end

Public Instance Methods

check_code(code) click to toggle source
# File lib/codebreaker/codebreaker.rb, line 38
def check_code(code)
  @codemaker.verify(code)
  dicrement_attemts unless win?
  save_stats if game_end?
  result_code
end
game_end?() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 69
def game_end?
  lose? || win?
end
hint() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 49
def hint
  return unless hint?

  res = @hint_cache.each_with_object(@codemaker.code.dup) do |index, object|
    object.delete_at(index)
  end
  index = rand(0..3)
  @hint_cache << index
  @hints -= 1
  res[index]
end
hint?() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 61
def hint?
  @hints.positive?
end
lose?() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 73
def lose?
  !win? && attempts.zero?
end
registration(name) click to toggle source
# File lib/codebreaker/codebreaker.rb, line 30
def registration(name)
  raise CustomErrors::NameInvalidError unless validate_name(name)

  @name = name.capitalize
end
result_code() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 45
def result_code
  @codemaker.verified_code
end
win?() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 65
def win?
  @codemaker.check? && attempts >= 0
end

Private Instance Methods

dicrement_attemts() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 79
def dicrement_attemts
  @attempts -= 1
end
save_stats() click to toggle source
# File lib/codebreaker/codebreaker.rb, line 83
def save_stats
  CodeBreaker.save(CodeBreaker.stats.push(
                     name: @name,
                     attempts_total: LEVEL[@difficulty][:attempts],
                     hints_total: LEVEL[@difficulty][:hints],
                     attempts_used: LEVEL[@difficulty][:attempts] - attempts,
                     hints_used: LEVEL[@difficulty][:hints] - @hints,
                     difficulty: @difficulty
                   ))
end
validate_name(name) click to toggle source
# File lib/codebreaker/codebreaker.rb, line 94
def validate_name(name)
  name.is_a?(String) &&
    validate_max_length(name, 20) &&
    validate_min_length(name, 4)
end