-
Notifications
You must be signed in to change notification settings - Fork 492
Expand file tree
/
Copy pathbowling.rb
More file actions
55 lines (45 loc) · 1.04 KB
/
bowling.rb
File metadata and controls
55 lines (45 loc) · 1.04 KB
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
52
53
54
55
class Bowling
def initialize
@rolls = []
end
def roll(pins)
@rolls << pins
end
def score
total_score = 0
roll_index = 0
(1..10).each do |_|
if strike?(roll_index)
total_score += 10 + strike_bonus(roll_index)
roll_index += 1
elsif spare?(roll_index)
total_score += 10 + spare_bonus(roll_index)
roll_index += 2
else
total_score += frame_score(roll_index)
roll_index += 2
end
end
total_score
end
private
def strike?(roll_index)
@rolls[roll_index].to_i == 10
end
def spare?(roll_index)
@rolls[roll_index].to_i + @rolls[roll_index + 1].to_i == 10
end
def strike_bonus(roll_index)
if roll_index == 18
@rolls[roll_index + 1].to_i + @rolls[roll_index + 2].to_i
else
@rolls[roll_index + 1].to_i + (@rolls[roll_index + 2].to_i || 0)
end
end
def spare_bonus(roll_index)
@rolls[roll_index + 2].to_i
end
def frame_score(roll_index)
@rolls[roll_index].to_i + @rolls[roll_index + 1].to_i
end
end