Class: Codebreaker::Game

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

Constant Summary collapse

ATTEMPTS_COUNT =
10
HINTS_COUNT =
3

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/codebreaker/game.rb', line 8

def initialize
  @secret_code = generate_code
  @attempt = 0
  @hint = 0
  @is_winner = false
end

Instance Attribute Details

#attemptObject (readonly)

Returns the value of attribute attempt.



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

def attempt
  @attempt
end

#hintObject (readonly)

Returns the value of attribute hint.



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

def hint
  @hint
end

#is_winnerObject (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_leftObject



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

def attempts_left
  ATTEMPTS_COUNT - @attempt
end

#ended?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/codebreaker/game.rb', line 56

def ended?
  ATTEMPTS_COUNT == @attempt || @is_winner
end

#generate_codeObject



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_leftObject



19
20
21
# File 'lib/codebreaker/game.rb', line 19

def hints_left
  HINTS_COUNT - @hint
end

#saveObject



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

Returns:

  • (Boolean)


52
53
54
# File 'lib/codebreaker/game.rb', line 52

def winner?
  @is_winner
end