class Codebreaker::Game
Constants
- CORRECT_SYMBOL
- INCORRECT_SYMBOL
- LENGTH_CODE
- STATE
- VALID_NUMBERS
Attributes
attempts[R]
difficulties[R]
hints[R]
number[R]
player[R]
state[R]
Public Class Methods
new(player, difficulties)
click to toggle source
# File lib/codebreaker.rb, line 18 def initialize(player, difficulties) @player = player @difficulties = difficulties @attempts = @difficulties.attempts @hints = @difficulties.hints @number = generator_secret_code @available_hints = @number.clone @state = STATE[:continue] end
Public Instance Methods
check_code(code)
click to toggle source
# File lib/codebreaker.rb, line 33 def check_code(code) return nil unless valid_code?(code) temp_code = code.chars guess_number = Array.new(LENGTH_CODE) { 0 } calc_and_mark_correct(temp_code, guess_number) + calc_and_mark_incorrect(temp_code, guess_number) end
decrease_attempts!()
click to toggle source
# File lib/codebreaker.rb, line 71 def decrease_attempts! @attempts -= 1 end
hint()
click to toggle source
# File lib/codebreaker.rb, line 28 def hint @hints -= 1 @available_hints.delete_at(rand(@available_hints.size)) end
hints?()
click to toggle source
# File lib/codebreaker.rb, line 60 def hints? !@hints.zero? end
lose?()
click to toggle source
# File lib/codebreaker.rb, line 64 def lose? return false unless @attempts.zero? @state = STATE[:lose] true end
to_h()
click to toggle source
# File lib/codebreaker.rb, line 41 def to_h { player: @player.name, difficulties: @difficulties.level, attempts_total: @difficulties.attempts, hints_total: @difficulties.hints, attempts_used: @difficulties.attempts - @attempts, hints_used: @difficulties.hints - @hints, state: @state } end
win?(code)
click to toggle source
# File lib/codebreaker.rb, line 53 def win?(code) return false unless code == @number.join @state = STATE[:win] true end
Private Instance Methods
calc_and_mark_correct(code, used)
click to toggle source
# File lib/codebreaker.rb, line 77 def calc_and_mark_correct(code, used) result = '' code.each_index do |index| next unless number[index] == code[index] result += CORRECT_SYMBOL code[index], used[index] = nil end result end
calc_and_mark_incorrect(code, used)
click to toggle source
# File lib/codebreaker.rb, line 88 def calc_and_mark_incorrect(code, used) result = '' number.each_index do |number_index| code_index = code.index(number[number_index]) next if code_index.nil? || used[number_index].nil? result += INCORRECT_SYMBOL code[code_index], used[number_index] = nil end result end
generator_secret_code()
click to toggle source
# File lib/codebreaker.rb, line 100 def generator_secret_code Array.new(4) { rand(VALID_NUMBERS).to_s } end
valid_code?(code)
click to toggle source
# File lib/codebreaker.rb, line 104 def valid_code?(code) Verifier.verify_valid_code(code) end