class Codebreaker::Game

Constants

ATTEMPT_NUMBER

Attributes

available_attempts[R]
hint[R]

Public Class Methods

new() click to toggle source
# File lib/rk/codebreaker/game.rb, line 8
def initialize
  @hint = true
  @available_attempts = ATTEMPT_NUMBER
  @result = ""
  @secret_code = generate_code
end

Public Instance Methods

check_input(code) click to toggle source
# File lib/rk/codebreaker/game.rb, line 15
def check_input(code)
  return 'Incorrect format' unless code_valid?(code)
  @available_attempts -= 1
  return check_matches(code)
end
check_matches(user_code) click to toggle source
# File lib/rk/codebreaker/game.rb, line 26
def check_matches(user_code)
  @result = ""
  return @result = '++++' if user_code == @secret_code
  sum_array = @secret_code.chars.zip(user_code.chars)
  exact_match_calculation(sum_array)
  just_match_calculation(sum_array)
  @result
end
hint_answer() click to toggle source
# File lib/rk/codebreaker/game.rb, line 21
def hint_answer
  @hint = false
  @secret_code.split('').sample
end
save_to_file(filename, username) click to toggle source
# File lib/rk/codebreaker/game.rb, line 35
def save_to_file(filename, username)
  File.open(filename, 'a') do |file|
    file.puts "#{username}|used attempts #{ATTEMPT_NUMBER - @available_attempts};"
  end
end

Private Instance Methods

code_valid?(code) click to toggle source
# File lib/rk/codebreaker/game.rb, line 61
def code_valid?(code)
  code.to_s.match(/^[1-6]{4}$/)
end
exact_match_calculation(array) click to toggle source
# File lib/rk/codebreaker/game.rb, line 47
def exact_match_calculation(array)
  array.delete_if { |secret_item, user_item| @result << '+' if secret_item == user_item }
end
generate_code() click to toggle source
# File lib/rk/codebreaker/game.rb, line 43
def generate_code
  (1..4).map { rand(1..6) }.join
end
just_match_calculation(array) click to toggle source
# File lib/rk/codebreaker/game.rb, line 51
def just_match_calculation(array)
  rest_secret_code, rest_user_code = array.transpose
  rest_secret_code.each do |item|
    position = rest_user_code.index(item)
    next unless position
    @result << '-'
    rest_user_code.delete_at(position)
  end
end