class Codebreaker::Game

Attributes

attempts_left[RW]
attempts_spent[RW]
hint_avaliable[RW]
secret_code[R]
won[RW]

Public Class Methods

new() click to toggle source
# File lib/codebreaker/game.rb, line 9
def initialize
  @hint_avaliable = true
  @secret_code = generate_code
  @attempts_spent = 0
  @attempts_left = 0
end

Public Instance Methods

code_hucked_with?(user_input) click to toggle source
# File lib/codebreaker/game.rb, line 58
def code_hucked_with?(user_input)
  to_array(user_input) == secret_code
end
delete_coincidence(code, user_input) click to toggle source
# File lib/codebreaker/game.rb, line 50
def delete_coincidence(code, user_input)
  code.zip(user_input).delete_if { |item| item[0] == item[1] }
end
delete_if_need(code,input) click to toggle source
# File lib/codebreaker/game.rb, line 43
def delete_if_need(code,input)
  code.each_with_index do |elem, i|
    next if input.count(elem).zero?
    code.delete_at(i) if code.count(elem) > input.count(elem)
  end
end
find_plus_minus(user_input) click to toggle source
# File lib/codebreaker/game.rb, line 33
def find_plus_minus(user_input)
  half_coincidence = delete_coincidence(secret_code, to_array(user_input))
  plus = '+' * (4 - half_coincidence.size)
  code_left = half_coincidence.transpose[0]
  input_left = half_coincidence.transpose[1]
  code_left = delete_if_need(code_left, input_left)
  minus = '-' * (code_left.size - without_minus_size(code_left, input_left))
  plus + minus
end
formated_hint() click to toggle source
# File lib/codebreaker/game.rb, line 68
def formated_hint
  hint = Array.new(4) { '*' }
  position = rand(0..3)
  hint[position] = @secret_code[position]
  hint.join
end
generate_code() click to toggle source
# File lib/codebreaker/game.rb, line 16
def generate_code
  Array.new(4).map { rand(1..6) }
end
process_hint() click to toggle source
# File lib/codebreaker/game.rb, line 62
def process_hint
  return 'no hint' unless @hint_avaliable
  @hint_avaliable = false
  formated_hint
end
reply(input) click to toggle source
# File lib/codebreaker/game.rb, line 20
def reply(input)
  return @won = :won if code_hucked_with? input
  return @won = :lose if @attempts_left.zero?
  route(input)
end
route(input) click to toggle source
# File lib/codebreaker/game.rb, line 26
def route(input)
  @attempts_left -= 1
  @attempts_spent += 1
  return find_plus_minus(input) if !!input.match(/[\d]/)
  process_hint
end
without_minus_size(code, input) click to toggle source
# File lib/codebreaker/game.rb, line 54
def without_minus_size(code, input)
  code.delete_if { |item| input.include?(item) }.size
end