Class: Codebreaker::Game

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

Constant Summary collapse

NUMBER_ATTEMPTS =
3
HINTS =
4

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGame

Returns a new instance of Game.



8
9
10
11
12
13
# File 'lib/test_my_gem/game.rb', line 8

def initialize
  @secret_code = random 
  @attempts = NUMBER_ATTEMPTS
  @hints = HINTS 
  @exit = false 
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



6
7
8
# File 'lib/test_my_gem/game.rb', line 6

def attempts
  @attempts
end

#hintsObject (readonly)

Returns the value of attribute hints.



6
7
8
# File 'lib/test_my_gem/game.rb', line 6

def hints
  @hints
end

#secret_codeObject (readonly)

Returns the value of attribute secret_code.



6
7
8
# File 'lib/test_my_gem/game.rb', line 6

def secret_code
  @secret_code
end

Instance Method Details

#exit?Boolean

Returns:

  • (Boolean)


65
66
67
# File 'lib/test_my_gem/game.rb', line 65

def exit?
  @exit
end

#exit_with_status(message) ⇒ Object



27
28
29
30
# File 'lib/test_my_gem/game.rb', line 27

def exit_with_status(message)
  @exit = true 
  @status = message 
end

#guess(code) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/test_my_gem/game.rb', line 19

def guess(code)
  no_attempts 
  @code = code.split('').map(&:to_i)
  @attempts -= 1
  win 
  mark
end

#hintObject



40
41
42
43
44
# File 'lib/test_my_gem/game.rb', line 40

def hint 
  return "You don't have any hints." if @hints == 0
  @hints -=1
  @secret_code.sample
end

#markObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/test_my_gem/game.rb', line 46

def mark
  array_code = Array.new(@code)
  array_secret_code = Array.new(@secret_code)
  answer = []
  array_code.zip(array_secret_code).each_with_index do |(code, secret_code), i|
    next if code != secret_code
      array_secret_code[i], array_code[i] = nil
      answer << '+'
  end
  array_code.compact!
  array_secret_code.compact!
  array_code.map do |code|
    index = code && array_secret_code.index(code)
    next unless index
      array_secret_code[index] = nil
      answer << '-'
  end
  answer.join if @exit == false
end

#no_attemptsObject



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

def no_attempts
  return exit_with_status('Game over! You have no more attempts') if @attempts == 0
end

#randomObject



15
16
17
# File 'lib/test_my_gem/game.rb', line 15

def random 
  [6,5,4,3]
end

#statistikObject



68
69
70
# File 'lib/test_my_gem/game.rb', line 68

def statistik
  "Status: #{@status}, Secret code: #{@secret_code}, attempts left: #{@attempts}, hints left: #{@hints}"
end

#winObject



32
33
34
# File 'lib/test_my_gem/game.rb', line 32

def win 
  return exit_with_status('Congratulations, you win!') if @code == @secret_code 
end