Skip to main content

ai_backgammon/
play.rs

1use crate::{Player, Point, Position};
2use std::fmt;
3
4#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
5pub enum Location {
6    Bar,
7    Point(Point),
8    Off,
9}
10
11impl fmt::Display for Location {
12    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
13        match self {
14            Self::Bar => formatter.write_str("bar"),
15            Self::Point(point) => point.fmt(formatter),
16            Self::Off => formatter.write_str("off"),
17        }
18    }
19}
20
21#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
22/// One checker movement using one die.
23pub struct Step {
24    from: Location,
25    to: Location,
26    die: u8,
27}
28
29impl Step {
30    /// Creates a structurally valid checker step.
31    ///
32    /// This does not test the step against a position. Use [`crate::Turn`] or
33    /// [`crate::Position::play`] when game-rule validation is required.
34    pub fn new(from: Location, to: Location, die: u8) -> Result<Self, StepError> {
35        if !(1..=6).contains(&die) || from == Location::Off || to == Location::Bar {
36            return Err(StepError);
37        }
38        Ok(Self { from, to, die })
39    }
40
41    pub const fn from(self) -> Location {
42        self.from
43    }
44
45    pub const fn to(self) -> Location {
46        self.to
47    }
48
49    pub const fn die(self) -> u8 {
50        self.die
51    }
52
53    pub(crate) const fn unchecked(from: Location, to: Location, die: u8) -> Self {
54        Self { from, to, die }
55    }
56}
57
58impl fmt::Display for Step {
59    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(formatter, "{}/{}", self.from, self.to)
61    }
62}
63
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub struct StepError;
66
67impl fmt::Display for StepError {
68    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
69        formatter.write_str("a checker step needs a valid die, source, and destination")
70    }
71}
72
73impl std::error::Error for StepError {}
74
75#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
76/// A complete turn, preserving the order in which its checker steps occur.
77pub struct Play {
78    steps: Vec<Step>,
79}
80
81impl Play {
82    /// Creates an ordered checker play without validating it against a position.
83    pub fn new(steps: Vec<Step>) -> Self {
84        Self { steps }
85    }
86
87    pub const fn pass() -> Self {
88        Self { steps: Vec::new() }
89    }
90
91    pub fn steps(&self) -> &[Step] {
92        &self.steps
93    }
94
95    pub fn len(&self) -> usize {
96        self.steps.len()
97    }
98
99    pub fn is_empty(&self) -> bool {
100        self.steps.is_empty()
101    }
102}
103
104impl fmt::Display for Play {
105    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
106        if self.steps.is_empty() {
107            return formatter.write_str("pass");
108        }
109        for (index, step) in self.steps.iter().enumerate() {
110            if index > 0 {
111                formatter.write_str(" ")?;
112            }
113            step.fmt(formatter)?;
114        }
115        Ok(())
116    }
117}
118
119#[derive(Clone, Debug, Eq, PartialEq)]
120/// One resulting position and every legal step sequence that reaches it.
121pub struct PlayOutcome {
122    position: Position,
123    sequences: Vec<Play>,
124}
125
126impl PlayOutcome {
127    pub(crate) fn new(position: Position, sequence: Play) -> Self {
128        Self {
129            position,
130            sequences: vec![sequence],
131        }
132    }
133
134    pub const fn position(&self) -> Position {
135        self.position
136    }
137
138    pub fn representative(&self) -> &Play {
139        &self.sequences[0]
140    }
141
142    pub fn sequences(&self) -> &[Play] {
143        &self.sequences
144    }
145
146    pub(crate) fn push(&mut self, sequence: Play) {
147        self.sequences.push(sequence);
148        self.sequences.sort();
149    }
150}
151
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum PlayError {
154    GameOver,
155    IllegalPlay,
156}
157
158impl fmt::Display for PlayError {
159    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::GameOver => formatter.write_str("the game is already over"),
162            Self::IllegalPlay => formatter.write_str("the play is not legal for these dice"),
163        }
164    }
165}
166
167impl std::error::Error for PlayError {}
168
169pub(crate) fn destination(player: Player, point: Point, die: u8) -> Location {
170    match player {
171        Player::White if point.number() <= die => Location::Off,
172        Player::White => Location::Point(Point::new(point.number() - die).expect("point is valid")),
173        Player::Black if point.number() + die > 24 => Location::Off,
174        Player::Black => Location::Point(Point::new(point.number() + die).expect("point is valid")),
175    }
176}