Class: Codebreaker::Game

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

Constant Summary collapse

DIFFICULTY_HASH =
{ easy: { attempts: 15, hints: 2 },
medium: { attempts: 10, hints: 1 },
hell: { attempts: 5, hints: 1 } }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Validations

included

Constructor Details

#initialize(user, difficulty, secret_code) ⇒ Game

Returns a new instance of Game.



16
17
18
19
20
21
22
23
# File 'lib/codebreaker/game.rb', line 16

def initialize(user, difficulty, secret_code)
  @user = user
  @difficulty = difficulty
  @secret_code = secret_code
  @attempts_used = 0
  @hints_used = []
  validate!
end

Instance Attribute Details

#attempts_usedObject

Returns the value of attribute attempts_used.



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

def attempts_used
  @attempts_used
end

#difficultyObject (readonly)

Returns the value of attribute difficulty.



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

def difficulty
  @difficulty
end

#hints_usedObject (readonly)

Returns the value of attribute hints_used.



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

def hints_used
  @hints_used
end

#secret_codeObject (readonly)

Returns the value of attribute secret_code.



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

def secret_code
  @secret_code
end

#userObject (readonly)

Returns the value of attribute user.



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

def user
  @user
end

Instance Method Details

#any_hints_left?Boolean

Returns:

  • (Boolean)


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

def any_hints_left?
  DIFFICULTY_HASH[difficulty][:hints] > hints_used.count
end

#check(guess) ⇒ Object



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

def check(guess)
  self.attempts_used += 1

  guess_array = guess.digits.reverse
  secret_code_array = secret_code.digits.reverse

  codechecker = Codechecker.new(guess_array, secret_code_array)
  codechecker.call
  codechecker.response
end

#lose?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/codebreaker/game.rb', line 54

def lose?
  attempts_used >= DIFFICULTY_HASH[difficulty][:attempts]
end

#take_hintObject



40
41
42
43
44
45
46
47
48
# File 'lib/codebreaker/game.rb', line 40

def take_hint
  secret_code_array = secret_code.digits.reverse
  hints_used.each do |hint_used|
    secret_code_array.delete_at(secret_code_array.index(hint_used))
  end
  hint = secret_code_array.sample
  hints_used << hint
  hint
end

#win?(guess) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/codebreaker/game.rb', line 50

def win?(guess)
  guess == secret_code
end