Class: Codebreaker::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/codebreaker/game.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGame

Returns a new instance of Game.



6
7
8
9
10
11
# 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

Instance Attribute Details

#hints_countObject (readonly)

Returns the value of attribute hints_count.



4
5
6
# File 'lib/codebreaker/game.rb', line 4

def hints_count
  @hints_count
end

#remaining_attemptsObject (readonly)

Returns the value of attribute remaining_attempts.



4
5
6
# File 'lib/codebreaker/game.rb', line 4

def remaining_attempts
  @remaining_attempts
end

#user_codeObject (readonly)

Returns the value of attribute user_code.



4
5
6
# File 'lib/codebreaker/game.rb', line 4

def user_code
  @user_code
end

Instance Method Details

#completed?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/codebreaker/game.rb', line 21

def completed?
  lost? || won?
end

#lost?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/codebreaker/game.rb', line 17

def lost?
  @remaining_attempts == 0
end

#mark_user_code(guess) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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_resultObject



59
60
61
62
63
64
65
66
67
68
69
# 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_hintObject



48
49
50
51
52
53
54
55
56
57
# 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?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/codebreaker/game.rb', line 13

def won?
  @user_code == '++++'
end