class Codebreaker::Game
Constants
- ATTEMPTS
- HINTS
Attributes
made_guesses[R]
used_attempts[R]
used_hints[R]
Public Class Methods
new()
click to toggle source
# File lib/codebreaker/game.rb, line 8 def initialize @secret_code = generate @shuffled_secret_code = @secret_code.shuffle @used_attempts = 0 @used_hints = 0 @made_guesses = {} end
Public Instance Methods
available_attempts()
click to toggle source
# File lib/codebreaker/game.rb, line 31 def available_attempts ATTEMPTS - @used_attempts end
available_hints()
click to toggle source
# File lib/codebreaker/game.rb, line 35 def available_hints HINTS - @used_hints end
hint()
click to toggle source
# File lib/codebreaker/game.rb, line 16 def hint @used_hints += 1 @shuffled_secret_code.pop end
make_guess(user_code)
click to toggle source
# File lib/codebreaker/game.rb, line 21 def make_guess(user_code) return unless code_valid?(user_code) @used_attempts += 1 @user_code = user_code.chars.map(&:to_i) return '++++' if @user_code == @secret_code result = exact_matches + number_matches @made_guesses[user_code] = result result end
Private Instance Methods
code_valid?(user_code)
click to toggle source
# File lib/codebreaker/game.rb, line 45 def code_valid?(user_code) user_code.match(/^[1-6]{4}$/) end
exact_matches()
click to toggle source
# File lib/codebreaker/game.rb, line 49 def exact_matches @zipped_codes = @secret_code.zip(@user_code).delete_if { |el| el[0] == el[1] } '+' * (@secret_code.length - @zipped_codes.length) end
generate()
click to toggle source
# File lib/codebreaker/game.rb, line 41 def generate Array.new(4) { rand(1..6) } end
number_matches()
click to toggle source
# File lib/codebreaker/game.rb, line 54 def number_matches transposed = @zipped_codes.transpose secret_array = transposed[0] user_array = transposed[1] user_array.each do |el| if secret_array.include?(el) index = secret_array.index(el) secret_array.delete_at(index) end end '-' * (@zipped_codes.length - secret_array.length) end