class Codebreaker::Game
Constants
- REMAINING_ATTEMPTS
Attributes
hints_count[R]
remaining_attempts[R]
user_code[R]
Public Class Methods
new()
click to toggle source
# File lib/codebreaker/game.rb, line 6 def initialize @secret_code, @user_code = ' ', ' ' @hints_count, @remaining_attempts = HINTS_COUNT, REMAINING_ATTEMPTS @started_at = Time.now start end
Public Instance Methods
completed?()
click to toggle source
# File lib/codebreaker/game.rb, line 21 def completed? lost? || won? end
lost?()
click to toggle source
# File lib/codebreaker/game.rb, line 17 def lost? @remaining_attempts == 0 end
mark_user_code(guess)
click to toggle source
# File lib/codebreaker/game.rb, line 25 def mark_user_code(guess) @user_code = '' guess = guess.chars secret = @secret_code.chars guess.each_with_index do |digit, index| next unless digit == secret[index] secret[index], guess[index] = nil @user_code << '+' end [secret, guess].each(&:compact!) secret.each do |digit| next unless guess.include?(digit) guess[guess.index(digit)] = nil @user_code << '-' end puts "Your code is: #{@user_code}" puts "Remaining attempts: #{@remaining_attempts -= 1}" end
save_result()
click to toggle source
# File lib/codebreaker/game.rb, line 59 def save_result time = playing_time puts 'Input your name: ' player_name = gets.chomp File.open('data.txt', 'a+') do |f| f.write "Name: #{player_name} \n" f.write "Playing time: #{time} sec \n\n" end end
show_hint()
click to toggle source
# File lib/codebreaker/game.rb, line 48 def show_hint return puts 'Hints are no longer available' if hints_count == 0 return puts 'You guessed all digits. pal. Just think a little bit.' if user_code =~ /^[+-]{4}/ puts '----------------------HINT----------------------' @secret_code.each_char.with_index(0) do |char, index| break puts "Unknown digit is: #{char}" unless user_code[index] =~ /[+-]/ end puts "Hints left: #{@hints_count -= 1}" end
won?()
click to toggle source
# File lib/codebreaker/game.rb, line 13 def won? @user_code == '++++' end
Private Instance Methods
playing_time()
click to toggle source
# File lib/codebreaker/game.rb, line 72 def playing_time (Time.now - @started_at).round end
start()
click to toggle source
# File lib/codebreaker/game.rb, line 76 def start @secret_code = Array.new(4) { rand(1..6) }.join end