Created
September 8, 2022 14:57
-
-
Save MRGRAVITY817/05fb8ebfaaafb2201a96e600ff4faafb to your computer and use it in GitHub Desktop.
Bowling Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub struct Game { | |
score: u32, | |
rolls: Vec<u32>, | |
} | |
impl Game { | |
pub fn new() -> Game { | |
Game { | |
score: 0, | |
rolls: vec![], | |
} | |
} | |
pub fn roll(&mut self, pin: u32) { | |
self.rolls.push(pin); | |
} | |
pub fn score(&mut self) -> u32 { | |
let mut round = 0; | |
(0..10).for_each(|_| { | |
if self.rolls[round] == 10 { | |
// strike | |
self.score += 10 + self.rolls[round + 1] + self.rolls[round + 2]; | |
round += 1; | |
} else if self.rolls[round] + self.rolls[round + 1] == 10 { | |
// spare | |
self.score += 10 + self.rolls[round + 2]; | |
round += 2; | |
} else { | |
self.score += self.rolls[round] + self.rolls[round + 1]; | |
round += 2; | |
} | |
}); | |
self.score | |
} | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn gutter_game() { | |
let mut game = Game::new(); | |
(0..20).for_each(|_| game.roll(0)); | |
assert_eq!(game.score(), 0) | |
} | |
#[test] | |
fn all_ones() { | |
let mut game = Game::new(); | |
(0..20).for_each(|_| game.roll(1)); | |
assert_eq!(game.score(), 20) | |
} | |
#[test] | |
fn one_spare() { | |
let mut game = Game::new(); | |
game.roll(5); | |
game.roll(5); // spare! | |
game.roll(4); // 4 * 2 = 8 | |
(0..17).for_each(|_| game.roll(0)); | |
assert_eq!(game.score(), 18) | |
} | |
#[test] | |
fn one_strike() { | |
let mut game = Game::new(); | |
game.roll(10); // strike! | |
game.roll(5); // 5 * 2 = 10 | |
game.roll(5); // 5 * 2 = 10 | |
(0..16).for_each(|_| game.roll(0)); | |
assert_eq!(game.score(), 30) | |
} | |
#[test] | |
fn two_strikes() { | |
let mut game = Game::new(); | |
game.roll(10); // strike! | |
game.roll(5); // 5 * 2 = 10 | |
game.roll(5); // 5 * 2 = 10 | |
game.roll(10); // strike * 2 = 20! | |
game.roll(2); // 2 * 2 = 4 | |
game.roll(3); // 3 * 2 = 6 | |
(0..14).for_each(|_| game.roll(0)); | |
assert_eq!(game.score(), 60) | |
} | |
#[test] | |
fn perfect_game() { | |
let mut game = Game::new(); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
game.roll(10); | |
assert_eq!(game.score(), 300) | |
} | |
} |
It was a useful study, thank you friend!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The best of the best