class Codebreakergem::Game
Constants
- CORRECT_PLACE_SYMBOL
- DIGIT_NUMBER
- FILE
- INCORRECT_PLACE_SYMBOL
- PERMITTED_CLASSES
Attributes
difficulty[RW]
secret_code[R]
statistics[RW]
user[R]
Public Class Methods
new(user, difficulty_title)
click to toggle source
# File lib/classes/game.rb, line 22 def initialize(user, difficulty_title) @user = user @difficulty = difficulty_factory(difficulty_title) @secret_code = generate_code end
Public Instance Methods
save()
click to toggle source
# File lib/classes/game.rb, line 48 def save FileWorker.add_to_file(FILE, to_h) end
show_hint()
click to toggle source
# File lib/classes/game.rb, line 28 def show_hint return I18n.t(:no_hints) unless difficulty.hints.positive? difficulty.hints -= 1 secret_code[difficulty.hints] end
to_h()
click to toggle source
# File lib/classes/game.rb, line 52 def to_h source = difficulty_factory(difficulty.title) formater(source, source.attempts - difficulty.attempts, source.hints - difficulty.hints) end
try_guess(guess)
click to toggle source
# File lib/classes/game.rb, line 35 def try_guess(guess) if guess == secret_code save difficulty.attempts = 0 return I18n.t(:victory_message) end difficulty.attempts -= 1 return I18n.t(:out_of_attempts) unless difficulty.attempts.positive? make_guess(guess) end
Private Instance Methods
difficulty_factory(difficulty_title)
click to toggle source
# File lib/classes/game.rb, line 103 def difficulty_factory(difficulty_title) case difficulty_title when 'Easy' then Easy.new when 'Medium' then Medium.new when 'Hell' then Hell.new end end
find_place(guess, code)
click to toggle source
# File lib/classes/game.rb, line 74 def find_place(guess, code) result = '' (0...guess.length).each do |index| next unless guess[index] == code[index] result += CORRECT_PLACE_SYMBOL code[index] = ' ' guess[index] = '_' end result end
find_presence(guess, code)
click to toggle source
# File lib/classes/game.rb, line 86 def find_presence(guess, code) result = '' (0...guess.length).each do |index| position = code.index(guess[index]) if position result += INCORRECT_PLACE_SYMBOL code[position] = ' ' end end result end
formater(source_difficulty, attempts_used, hints_used)
click to toggle source
# File lib/classes/game.rb, line 59 def formater(source_difficulty, attempts_used, hints_used) { name: user.name, difficulty: difficulty.title, order: difficulty.order, attempts_total: source_difficulty.attempts, attempts_used: attempts_used, hints_total: source_difficulty.hints, hints_used: hints_used, game_time: Time.now.strftime('%Y.%m.%d - %H:%M:%S') } end
generate_code()
click to toggle source
# File lib/classes/game.rb, line 70 def generate_code DIGIT_NUMBER.times.map { rand(1..6) }.join end
make_guess(guess)
click to toggle source
# File lib/classes/game.rb, line 98 def make_guess(guess) code_copy = secret_code.dup find_place(guess, code_copy) + find_presence(guess, code_copy) end