class CodebreakerVk::Game
Constants
- DIFFICULTY_LEVEL
- GOT_IT
- NOT_YET
- RANGE_END
- RANGE_START
- SECRET_CODE_LENGTH
Attributes
attempts[RW]
attempts_total[RW]
difficulty[RW]
hints[RW]
hints_total[RW]
name[RW]
secret[RW]
Public Class Methods
new(name:, difficulty:)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 19 def initialize(name:, difficulty:) @name = name @difficulty = difficulty @attempts = DIFFICULTY_LEVEL[difficulty][:attempts] @hints = DIFFICULTY_LEVEL[difficulty][:hints] @secret = make_number @unused_hints = @secret.chars end
Public Instance Methods
check(number)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 32 def check(number) @attempts -= 1 @last_result = check_numbers(@secret.chars, number.chars) end
make_number(numbers = RANGE_END)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 28 def make_number(numbers = RANGE_END) (1..SECRET_CODE_LENGTH).map { rand(RANGE_START..numbers) }.join end
use_hint()
click to toggle source
# File lib/codebreaker_vk/game.rb, line 41 def use_hint return I18n.t(:no_hints) unless @hints.positive? @hints -= 1 hint(@unused_hints) end
win?()
click to toggle source
# File lib/codebreaker_vk/game.rb, line 37 def win? @last_result == GOT_IT * SECRET_CODE_LENGTH end
Private Instance Methods
check_numbers(secret, numbers)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 50 def check_numbers(secret, numbers) exact_matches, non_exact_matches = secret.zip(numbers).partition do |secret_number, input_number| secret_number == input_number end result = Array.new(exact_matches.count, GOT_IT) find_non_exact_matches(result, non_exact_matches) if non_exact_matches.any? result.join end
find_non_exact_matches(result, non_exact_matches)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 62 def find_non_exact_matches(result, non_exact_matches) secret, numbers = non_exact_matches.transpose numbers.each do |number_element| next unless secret.include? number_element result.push(NOT_YET) && secret.delete_at(secret.index(number_element)) end end
hint(secret)
click to toggle source
# File lib/codebreaker_vk/game.rb, line 71 def hint(secret) secret.shuffle.pop end