Class: Codebreaker::Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(writer = GameWriter.new, player_class = Player) ⇒ Game

Returns a new instance of Game.



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

def initialize(writer = GameWriter.new, player_class = Player)
  @writer       = writer
  @player_class = player_class
end

Instance Attribute Details

#hints_leftObject (readonly)

Returns the value of attribute hints_left.



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

def hints_left
  @hints_left
end

#tries_leftObject (readonly)

Returns the value of attribute tries_left.



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

def tries_left
  @tries_left
end

Instance Method Details

#answerObject



53
54
55
# File 'lib/ep-codebreaker/game.rb', line 53

def answer
  @code if finished?
end

#as_jsonObject



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/ep-codebreaker/game.rb', line 65

def as_json
  {
    result: nil,
    hint: nil,
    tries_left: @tries_left,
    hints_left: @hints_left,
    finished: finished?,
    won: won?,
    answer: answer
  }
end

#check_guess(input) ⇒ Object



32
33
34
35
36
# File 'lib/ep-codebreaker/game.rb', line 32

def check_guess(input)
  verify input
  @tries_left -= 1
  @result = check_input(@code.chars, input.chars)
end

#finished?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/ep-codebreaker/game.rb', line 45

def finished?
  @tries_left.zero? || won?
end

#high_scoresObject



61
62
63
# File 'lib/ep-codebreaker/game.rb', line 61

def high_scores
  @writer.load_scores
end

#hintObject



38
39
40
41
42
43
# File 'lib/ep-codebreaker/game.rb', line 38

def hint
  return false if @hints_left.zero?
  @tries_left -= 1
  @hints_left -= 1
  generate_hint
end

#save_score(name) ⇒ Object



57
58
59
# File 'lib/ep-codebreaker/game.rb', line 57

def save_score(name)
  @writer.write @player_class.new(name, @tries_left, @hints_left)
end

#startObject



24
25
26
27
28
29
30
# File 'lib/ep-codebreaker/game.rb', line 24

def start
  @code             = Array.new(LENGTH) { rand(MIN..MAX) }.join
  @result           = ''
  @tries_left       = TRIES
  @hints_left       = HINTS
  @indexes_for_hint = (0...LENGTH).to_a
end

#to_json(*options) ⇒ Object



77
78
79
# File 'lib/ep-codebreaker/game.rb', line 77

def to_json(*options)
  as_json.to_json(*options)
end

#won?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/ep-codebreaker/game.rb', line 49

def won?
  @result == ('+' * LENGTH)
end