Class: Codebreaker::Game
- Inherits:
-
Object
- Object
- Codebreaker::Game
- Defined in:
- lib/codebreaker/game.rb
Constant Summary collapse
- ATTEMPTS_COUNT =
10- HINTS_COUNT =
3
Instance Attribute Summary collapse
-
#attempt ⇒ Object
readonly
Returns the value of attribute attempt.
-
#hint ⇒ Object
readonly
Returns the value of attribute hint.
-
#is_winner ⇒ Object
readonly
Returns the value of attribute is_winner.
Instance Method Summary collapse
- #attempts_left ⇒ Object
- #ended? ⇒ Boolean
- #generate_code ⇒ Object
- #guess(input) ⇒ Object
- #hints_left ⇒ Object
-
#initialize ⇒ Game
constructor
A new instance of Game.
- #save ⇒ Object
- #winner? ⇒ Boolean
Constructor Details
#initialize ⇒ Game
Returns a new instance of Game.
8 9 10 11 12 13 |
# File 'lib/codebreaker/game.rb', line 8 def initialize @secret_code = generate_code @attempt = 0 @hint = 0 @is_winner = false end |
Instance Attribute Details
#attempt ⇒ Object (readonly)
Returns the value of attribute attempt.
6 7 8 |
# File 'lib/codebreaker/game.rb', line 6 def attempt @attempt end |
#hint ⇒ Object (readonly)
Returns the value of attribute hint.
6 7 8 |
# File 'lib/codebreaker/game.rb', line 6 def hint @hint end |
#is_winner ⇒ Object (readonly)
Returns the value of attribute is_winner.
6 7 8 |
# File 'lib/codebreaker/game.rb', line 6 def is_winner @is_winner end |
Instance Method Details
#attempts_left ⇒ Object
15 16 17 |
# File 'lib/codebreaker/game.rb', line 15 def attempts_left ATTEMPTS_COUNT - @attempt end |
#ended? ⇒ Boolean
56 57 58 |
# File 'lib/codebreaker/game.rb', line 56 def ended? ATTEMPTS_COUNT == @attempt || @is_winner end |
#generate_code ⇒ Object
23 24 25 |
# File 'lib/codebreaker/game.rb', line 23 def generate_code @secret_code = Array.new(4){ rand(6) + 1 }.join end |
#guess(input) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/codebreaker/game.rb', line 27 def guess(input) return if input.length != 4 @attempt += 1 secret = @secret_code.chars.map(&:to_i) result = [] input.chars.map(&:to_i).each_with_index do |digit, index| if digit == secret[index] secret[index] = nil result << '+' elsif secret.include? digit secret[secret.find_index(digit)] = nil result << '-' end end normalized_output = result.sort.join @is_winner = true if normalized_output == '++++' normalized_output end |
#hints_left ⇒ Object
19 20 21 |
# File 'lib/codebreaker/game.rb', line 19 def hints_left HINTS_COUNT - @hint end |
#save ⇒ Object
60 61 62 63 64 |
# File 'lib/codebreaker/game.rb', line 60 def save YAML::Store.new('storage/storage.yml').transaction do |storage| storage[Time.now] = "attempts taken: #{@attempt}; hints used: #{@hint}; result: #{(winner? ? 'won' : 'loose')}" end end |
#winner? ⇒ Boolean
52 53 54 |
# File 'lib/codebreaker/game.rb', line 52 def winner? @is_winner end |