-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.rb
51 lines (40 loc) · 1.04 KB
/
game.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require_relative "frame"
class Game
TOTAL_FRAMES = 10
attr_reader :score
def initialize
@frames = [Frame.new]
@score = 0
end
def throw! knocked_pins:
raise(GameError, "The game is over, no more throws allowed.") if game_over?
@frames.last.throw! knocked_pins: knocked_pins
update_old_frames_with knocked_pins
start_new_frame if @frames.last.over? && reached_last_frame?.!
update_score
end
def game_over?
reached_last_frame? && @frames.last.over?
end
private
def update_old_frames_with added_points
old_frames = @frames.slice(0, (@frames.length-1)).to_a
old_frames.each do |old_frame|
old_frame.update_extra_score added_points: added_points
end
end
def update_score
@score = @frames.map(&:score).inject(&:+)
end
def start_new_frame
@frames << (Frame.new last: reached_before_last_frame?)
end
def reached_last_frame?
@frames.count == TOTAL_FRAMES
end
def reached_before_last_frame?
@frames.count == TOTAL_FRAMES-1
end
end
class GameError < StandardError
end