Class: Codebreaker::Game

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

Constant Summary collapse

DIFFICULTIES =
{
  easy: { attempts: 30, hints: 3 },
  medium: { attempts: 15, hints: 2 },
  hard: { attempts: 10, hints: 1 }
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret_code, attempts, hints) ⇒ Game

Returns a new instance of Game.



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

def initialize(secret_code, attempts, hints)
  @secret_code = secret_code
  @attempts = attempts
  @hints = hints
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



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

def attempts
  @attempts
end

#hintsObject (readonly)

Returns the value of attribute hints.



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

def hints
  @hints
end

#secret_codeObject (readonly)

Returns the value of attribute secret_code.



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

def secret_code
  @secret_code
end

#user_codeObject

Returns the value of attribute user_code.



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

def user_code
  @user_code
end

Class Method Details

.generate_game_data(difficulty = :easy) ⇒ Object



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

def self.generate_game_data(difficulty = :easy)
  data = Hash.new(Array.new(4) { rand(1..6) })
  data[:attempts] = DIFFICULTIES.dig(difficulty, :attempts)
  data[:hints] = data.default.shuffle.take(DIFFICULTIES.dig(difficulty, :hints))
  data
end

Instance Method Details

#equal_codes?(user_answer) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/codebreaker/game.rb', line 43

def equal_codes?(user_answer)
  secret_code.join == user_answer
end

#handle_guess(user_answer) ⇒ Object



28
29
30
31
32
33
# File 'lib/codebreaker/game.rb', line 28

def handle_guess(user_answer)
  @user_code = user_answer.each_char.map(&:to_i)
  handle_numbers
  @attempts -= 1
  @round_result.empty? ? 'No matches' : @round_result
end

#take_a_hint!Object



39
40
41
# File 'lib/codebreaker/game.rb', line 39

def take_a_hint!
  @hints.pop
end

#valid_answer?(user_answer) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/codebreaker/game.rb', line 35

def valid_answer?(user_answer)
  user_answer =~ /^[1-6]{4}$/
end