1use crate::{Dice, DiceError, GameOutcome, Play, PlayError, Player, Position};
2use std::fmt;
3
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
6pub enum GamePhase {
7 OpeningRoll,
8 PreRoll,
9 CheckerPlay(Dice),
10 GameOver(GameOutcome),
11}
12
13#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct Game {
16 position: Position,
17 phase: GamePhase,
18}
19
20impl Default for Game {
21 fn default() -> Self {
22 Self::new()
23 }
24}
25
26impl Game {
27 pub const fn new() -> Self {
28 Self {
29 position: Position::new(),
30 phase: GamePhase::OpeningRoll,
31 }
32 }
33
34 pub const fn position(&self) -> Position {
35 self.position
36 }
37
38 pub const fn phase(&self) -> GamePhase {
39 self.phase
40 }
41
42 pub fn restart(&mut self) {
43 *self = Self::new();
44 }
45
46 pub fn opening_roll(&mut self, white: u8, black: u8) -> Result<bool, GameError> {
48 if self.phase != GamePhase::OpeningRoll {
49 return Err(GameError::WrongPhase);
50 }
51 let dice = Dice::new(white, black)?;
52 if white == black {
53 return Ok(false);
54 }
55 self.position.set_side_to_move(if white > black {
56 Player::White
57 } else {
58 Player::Black
59 });
60 self.phase = GamePhase::CheckerPlay(dice);
61 Ok(true)
62 }
63
64 pub fn roll(&mut self, dice: Dice) -> Result<(), GameError> {
66 if self.phase != GamePhase::PreRoll {
67 return Err(GameError::WrongPhase);
68 }
69 self.phase = GamePhase::CheckerPlay(dice);
70 Ok(())
71 }
72
73 pub fn legal_plays(&self) -> Vec<Play> {
74 match self.phase {
75 GamePhase::CheckerPlay(dice) => self.position.legal_plays(dice),
76 _ => Vec::new(),
77 }
78 }
79
80 pub fn play(&mut self, play: &Play) -> Result<(), GameError> {
82 let GamePhase::CheckerPlay(dice) = self.phase else {
83 return Err(GameError::WrongPhase);
84 };
85 self.position = self.position.play(dice, play)?;
86 self.phase = self
87 .position
88 .game_outcome()
89 .map_or(GamePhase::PreRoll, GamePhase::GameOver);
90 Ok(())
91 }
92}
93
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95pub enum GameError {
96 WrongPhase,
97 InvalidDice(DiceError),
98 InvalidPlay(PlayError),
99}
100
101impl From<DiceError> for GameError {
102 fn from(error: DiceError) -> Self {
103 Self::InvalidDice(error)
104 }
105}
106
107impl From<PlayError> for GameError {
108 fn from(error: PlayError) -> Self {
109 Self::InvalidPlay(error)
110 }
111}
112
113impl fmt::Display for GameError {
114 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::WrongPhase => formatter.write_str("that action is not available in this phase"),
117 Self::InvalidDice(error) => error.fmt(formatter),
118 Self::InvalidPlay(error) => error.fmt(formatter),
119 }
120 }
121}
122
123impl std::error::Error for GameError {}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128 use crate::GameKind;
129
130 #[test]
131 fn a_natural_gammon_ends_the_game() {
132 let mut points = [0_i8; 24];
133 points[0] = 1;
134 points[18] = -15;
135 let position = Position::from_parts(points, [0, 0], [14, 0], Player::White).unwrap();
136 let mut game = Game {
137 position,
138 phase: GamePhase::CheckerPlay(Dice::new(6, 5).unwrap()),
139 };
140
141 let play = game.legal_plays().remove(0);
142 game.play(&play).unwrap();
143
144 let GamePhase::GameOver(outcome) = game.phase() else {
145 panic!("the game should be over");
146 };
147 assert_eq!(outcome.winner, Player::White);
148 assert_eq!(outcome.kind, GameKind::Gammon);
149 }
150}