aboutsummaryrefslogtreecommitdiff
path: root/rust/bowling/src/lib.rs
blob: bd517a5125dbb23a51fd9ed3727742cac1dcef6f (plain) (blame)
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
#[derive(Debug, PartialEq)]
pub enum Error {
    NotEnoughPinsLeft,
    GameComplete,
}

#[derive(Debug, Default)]
pub struct BowlingGame {
    throws: Vec<u16>,
    prev: u16
}

impl BowlingGame {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn roll(&mut self, pins: u16) -> Result<(), Error> {
        if pins + self.prev > 10 {
            Err(Error::NotEnoughPinsLeft)
        } else if self.score().is_some() {
            Err(Error::GameComplete)
        } else {
            self.throws.push(pins);
            self.prev = if self.prev + pins == 10 { 0 } else { pins };
            Ok(())
        }
    }

    pub fn score(&self) -> Option<u16> {
        let mut score = 0;
        let mut stage = 0;
        for _ in 1..=10 {
            let first = self.throws.get(stage)?;
            let second = self.throws.get(stage+1)?;
            score += first + second;
            if first + second >= 10 {
                let third = self.throws.get(stage+2)?;
                score += third;
            }
            stage += if *first == 10 { 1 } else { 2 };
        }
        Some(score)
    }
}