Skip to content

Commit 9ec9ccd

Browse files
committed
refactor
1 parent f213dc3 commit 9ec9ccd

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

rust/bowling/src/lib.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ pub enum Error {
77
pub struct BowlingGame {
88
frames: Vec<Frame>,
99
previous_roll: Option<u16>,
10-
fill_ball1: Option<u16>
10+
fill_ball1: Option<u16>,
11+
fill_ball2: Option<u16>
1112
}
1213

1314
impl BowlingGame {
@@ -16,19 +17,31 @@ impl BowlingGame {
1617
frames: vec!(),
1718
previous_roll: None,
1819
fill_ball1: None,
20+
fill_ball2: None,
1921
}
2022
}
2123

2224
pub fn roll(&mut self, pins: u16) -> Result<(), Error> {
23-
// allower the user to roll again if they scored a strike or spare in the last frame.
24-
if self.frames.last().is_some_and(|x| x.is_spare()) {
25-
self.fill_ball1 = Some(pins);
26-
} else if self.is_game_over() {
25+
if self.is_game_over() {
2726
return Err(Error::GameComplete)
2827
}
2928
if pins > 10 {
3029
return Err(Error::NotEnoughPinsLeft)
3130
}
31+
32+
// Handle fill balls
33+
if self.frames.last().is_some_and(|x| x.is_spare()) {
34+
self.fill_ball1 = Some(pins);
35+
}
36+
if self.frames.last().is_some_and(|x| x.is_strike()) {
37+
if self.fill_ball1.is_none() {
38+
self.fill_ball1 = Some(pins);
39+
} else {
40+
self.fill_ball2 = Some(pins);
41+
}
42+
}
43+
44+
// Handle normal rolls
3245
if pins == 10 {
3346
let frame = Frame::new(pins, None);
3447
self.frames.push(frame);
@@ -52,8 +65,7 @@ impl BowlingGame {
5265
for (i, frame) in self.frames.iter().enumerate() {
5366
let next_frame = self.frames.get(i+1);
5467
if next_frame.is_none() {
55-
// TODO: implement fill balls
56-
total += frame.score(self.fill_ball1.unwrap_or(0), 0);
68+
total += frame.score(self.fill_ball1.unwrap_or(0), self.fill_ball2.unwrap_or(0));
5769
} else {
5870
let next_roll1 = next_frame.unwrap().roll1;
5971
let next_roll2 = next_frame.unwrap().roll2.unwrap();
@@ -70,6 +82,9 @@ impl BowlingGame {
7082
if self.frames.last().is_some_and(|x| x.is_spare()) && self.fill_ball1.is_none() {
7183
return false
7284
}
85+
if self.frames.last().is_some_and(|x| x.is_strike()) && self.fill_ball2.is_none() {
86+
return false
87+
}
7388
return true
7489
}
7590
}

0 commit comments

Comments
 (0)