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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use crate::{Frame, Game, Score};
/// Trait for all [ScoreProvider]s.
pub trait ScoreProvider: Clone + Copy {
/// Calculate the score for each [Frame] of a [Game].
fn computed(&self, game: &Game) -> Vec<usize>;
/// Caculate the current score for a [Game].
fn score(&self, game: &Game) -> usize {
let computed = self.computed(game);
if let Some(score) = computed.last() {
return *score;
}
0
}
/// Calculate the maximum score achievable for a [Game].
fn max(&self, game: &Game, provider: &impl ScoreProvider) -> usize;
}
/// [ScoreProvider] for classic 10-pin bowling.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TenPinScoreProvider;
impl ScoreProvider for TenPinScoreProvider {
fn computed(&self, game: &Game) -> Vec<usize> {
let mut frames = vec![];
let mut score = 0;
for i in 0..game.frame_count {
if let Some(frame) = game.frame(i) {
// Add frame's score
score += frame.value();
// Add bonus points
if i < game.frame_count - 1 {
if let Some(next) = game.frame(i + 1) {
if frame.is_spare() {
score += next.first.value();
} else if frame.is_strike() {
score += next.first.value();
if next.is_strike() {
if i == game.frame_count - 2 {
score += next.second.value();
} else {
if let Some(next2) = game.frame(i + 2) {
score += next2.first.value();
}
}
} else if next.is_spare() {
score += 10 - next.first.value();
} else {
score += next.second.value();
}
}
}
}
println!("({}): {} -> {}", i, frame, score);
frames.push(score);
}
}
frames
}
fn max(&self, game: &Game, provider: &impl ScoreProvider) -> usize {
let mut frames = vec![];
for i in 0..game.frame_count {
if let Some(frame) = game.frame(i) {
if i == game.frame_count - 1 {
let mut f = frame.clone();
if f.first == Score::EMPTY {
f.first = Score::STRIKE;
}
if f.second == Score::EMPTY {
if f.first == Score::STRIKE {
f.second = Score::STRIKE;
} else {
f.second = Score::SPARE;
}
}
if let Some(bonus) = frame.bonus {
if bonus == Score::EMPTY {
if f.second.is_strike() {
f.bonus = Some(Score::STRIKE);
} else {
f.bonus = Some(Score::SPARE);
}
}
} else {
if f.second.is_strike() {
f.bonus = Some(Score::STRIKE);
} else {
f.bonus = Some(Score::SPARE);
}
}
frames.push(f);
} else {
if frame.first.is_strike() {
frames.push(Frame::strike());
} else if frame.second == Score::EMPTY {
frames.push(Frame::spare(frame.first.value()))
} else {
frames.push(frame.clone());
}
}
} else {
if i == game.frame_count - 1 {
frames.push(Frame::triple_strike());
} else {
frames.push(Frame::strike());
}
}
}
Game::with_frame_count(game.frame_count, frames).score_with_provider(*provider)
}
}