class CodebreakerAp::Game

Constants

CODE_LENGTH
CODE_LENGTH_RANGE
IN_POSITION
LOCALES_FOLDER
NOT_IN_POSITION
SECRET_CODE_NUMBERS_RANGE

Attributes

difficulty[R]
secret_code[R]

Public Class Methods

new() click to toggle source
# File lib/codebreaker_ap/game.rb, line 15
def initialize
  @difficulty = CodebreakerAp::Difficulty.new
  @secret_code = generate_secret_code
  @hints_code = secret_code.to_a.dup.shuffle
  @game_win = false
end

Public Instance Methods

check_answer(answer) click to toggle source
# File lib/codebreaker_ap/game.rb, line 22
def check_answer(answer)
  answer = answer.to_s

  @game_win = true if @secret_code.join == answer
  @difficulty.attempts -= 1

  compare_answer_with_secret(answer.split(''), secret_code.join.split(''))
end
show_rules() click to toggle source
# File lib/codebreaker_ap/game.rb, line 39
def show_rules
  rules = read_from_file("#{LOCALES_FOLDER}/#{Message.new.file_rules}")
  return unless rules

  rules
end
take_hint() click to toggle source
# File lib/codebreaker_ap/game.rb, line 35
def take_hint
  difficulty.hint(@hints_code)
end
win?() click to toggle source
# File lib/codebreaker_ap/game.rb, line 31
def win?
  @game_win
end

Private Instance Methods

compare_answer_with_secret(answer_array, secret_code_array) click to toggle source
# File lib/codebreaker_ap/game.rb, line 48
def compare_answer_with_secret(answer_array, secret_code_array)
  (position_matches(answer_array, secret_code_array) + other_matches(answer_array, secret_code_array)).join('')
end
generate_secret_code() click to toggle source
# File lib/codebreaker_ap/game.rb, line 77
def generate_secret_code
  CODE_LENGTH_RANGE.map { rand(SECRET_CODE_NUMBERS_RANGE) }
end
other_matches(answer_array, secret_code_array) click to toggle source
# File lib/codebreaker_ap/game.rb, line 64
def other_matches(answer_array, secret_code_array)
  matches = []
  answer_array.each do |value|
    next if value.nil?

    if secret_code_array.include? value
      secret_code_array[secret_code_array.find_index(value)] = nil
      matches.push(NOT_IN_POSITION)
    end
  end
  matches
end
position_matches(answer_array, secret_code_array) click to toggle source
# File lib/codebreaker_ap/game.rb, line 52
def position_matches(answer_array, secret_code_array)
  matches = []
  answer_array.each_with_index do |value, index|
    next if value != secret_code_array[index]

    secret_code_array[index] = nil
    answer_array[index] = nil
    matches.push(IN_POSITION)
  end
  matches
end