Skip to main content

hearts_engine/
driver.rs

1//! The [`Table`] driver: applies strategy decisions to a round
2//!
3//! The driver owns the [`Round`] and the common-knowledge void table, asks
4//! the acting strategy for one decision at a time, validates it, applies
5//! it, and keeps the void inference current — so information hygiene holds
6//! by construction for any [`Strategy`].
7
8use crate::{Strategy, View};
9use hearts::round::RoundError;
10use hearts::{Hand, Phase, Round, RoundResult, Seat};
11use thiserror::Error;
12
13/// An error while driving a round
14#[derive(Debug, Error)]
15#[non_exhaustive]
16pub enum EngineError {
17    /// A strategy chose an action the round rejected
18    #[error("{seat} chose an illegal action")]
19    IllegalAction {
20        /// The seat whose strategy misbehaved
21        seat: Seat,
22        /// The round's rejection
23        #[source]
24        source: RoundError,
25    },
26}
27
28/// A round in progress, with common-knowledge void tracking
29///
30/// [`Table::round`] intentionally exposes the full position — user
31/// interfaces and loggers need it — but strategies only ever receive the
32/// [`View`]s handed to them by [`Table::step`].
33#[derive(Debug, Clone)]
34pub struct Table {
35    round: Round,
36    /// Bit `suit as u8` of `voids[seat as usize]`: seat shown void in suit.
37    voids: [u8; 4],
38    scores: [u16; 4],
39}
40
41/// Recover the void table from the public trick history.
42fn infer_voids(round: &Round) -> [u8; 4] {
43    let mut voids = [0u8; 4];
44    for trick in round.tricks().iter().copied().chain(round.current_trick()) {
45        let Some(led) = trick.suit() else { continue };
46        for (seat, card) in trick.plays() {
47            if card.suit != led {
48                voids[seat as usize] |= 1 << led as u8;
49            }
50        }
51    }
52    voids
53}
54
55impl Table {
56    /// Wrap a round, recovering void inference from its history
57    ///
58    /// Unlike gin rummy, every observation in Hearts is public, so a table
59    /// can pick up a round in any phase.
60    ///
61    /// The game score defaults to level (all seats at zero), so a
62    /// standalone round reports [`game_scores`](View::game_scores) of
63    /// `[0; 4]`.  Set it with [`Table::scores`] when driving a round within
64    /// a game.
65    #[must_use]
66    pub fn new(round: Round) -> Self {
67        Self {
68            voids: infer_voids(&round),
69            round,
70            scores: [0; 4],
71        }
72    }
73
74    /// Set the running game totals, indexed by [`Seat`]
75    ///
76    /// Each seat's [`View`] then reports the seat-relative
77    /// [`game_scores`](View::game_scores), letting score-aware strategies
78    /// hunt the leader or duck for the endgame.
79    #[must_use]
80    pub const fn scores(mut self, scores: [u16; 4]) -> Self {
81        self.scores = scores;
82        self
83    }
84
85    /// Shuffle and deal a fresh round onto a new table
86    #[cfg(feature = "rand")]
87    #[must_use]
88    pub fn deal(
89        rules: hearts::Rules,
90        direction: hearts::PassDirection,
91        rng: &mut (impl rand::Rng + ?Sized),
92    ) -> Self {
93        Self::new(Round::deal(rules, direction, rng))
94    }
95
96    /// The underlying round, fully visible
97    #[must_use]
98    pub const fn round(&self) -> &Round {
99        &self.round
100    }
101
102    /// The seat the driver acts for next, or `None` when the round is over
103    ///
104    /// During the passing phase — where seats act concurrently in real play
105    /// — the driver serializes deterministically: the first unpassed seat
106    /// in [`Seat::ALL`] order.
107    #[must_use]
108    pub fn turn(&self) -> Option<Seat> {
109        match self.round.phase() {
110            Phase::Passing => Seat::ALL
111                .into_iter()
112                .find(|&seat| self.round.passed(seat).is_none()),
113            Phase::Playing => self.round.turn(),
114            Phase::Finished => None,
115        }
116    }
117
118    /// Whether every penalty card already sits in a completed trick, freezing
119    /// the round's point tally
120    ///
121    /// True only mid-play: once it holds, the remaining tricks are all
122    /// scoreless and cannot change any seat's result, so an interactive caller
123    /// may offer to end the round and jump straight to the outcome.  Reads the
124    /// won tricks, not [`Round::played`], so it stays false while the last
125    /// penalty card is still in the live, unresolved trick.
126    #[must_use]
127    pub fn points_settled(&self) -> bool {
128        self.round.phase() == Phase::Playing
129            && Seat::ALL
130                .into_iter()
131                .map(|seat| u16::from(self.round.points_taken(seat)))
132                .sum::<u16>()
133                == 26
134    }
135
136    /// The legally visible information for one seat
137    #[must_use]
138    pub const fn view(&self, seat: Seat) -> View<'_> {
139        let scores = [
140            self.scores[seat as usize],
141            self.scores[seat.left() as usize],
142            self.scores[seat.across() as usize],
143            self.scores[seat.right() as usize],
144        ];
145        View::new(&self.round, seat, &self.voids, scores)
146    }
147
148    /// Ask `strategy` — which must belong to the seat to act (see
149    /// [`Table::turn`]) — for one decision and apply it
150    ///
151    /// Returns the result once the round finishes, `None` while it
152    /// continues.
153    ///
154    /// # Errors
155    ///
156    /// [`EngineError::IllegalAction`] when the round rejects the strategy's
157    /// choice — including a pass of non-distinct cards.  The table is left
158    /// unchanged, so an interactive caller may retry the same decision.
159    pub fn step(
160        &mut self,
161        strategy: &mut dyn Strategy,
162    ) -> Result<Option<RoundResult>, EngineError> {
163        let Some(seat) = self.turn() else {
164            return Ok(self.round.result());
165        };
166        let reject = |source| EngineError::IllegalAction { seat, source };
167
168        match self.round.phase() {
169            Phase::Passing => {
170                // Duplicate cards collapse in the set and fail the
171                // three-card check inside the round.
172                let cards: Hand = strategy.pass_cards(&self.view(seat)).into_iter().collect();
173                self.round.pass(seat, cards).map_err(reject)?;
174            }
175            Phase::Playing => {
176                let card = strategy.play_card(&self.view(seat));
177                let led = self.round.current_trick().and_then(|trick| trick.suit());
178                self.round.play(seat, card).map_err(reject)?;
179                if let Some(led) = led
180                    && card.suit != led
181                {
182                    self.voids[seat as usize] |= 1 << led as u8;
183                }
184            }
185            Phase::Finished => {}
186        }
187        Ok(self.round.result())
188    }
189
190    /// Drive the round to completion, one strategy per seat
191    ///
192    /// # Errors
193    ///
194    /// [`EngineError::IllegalAction`] when a strategy's choice is rejected.
195    pub fn play(&mut self, strategies: [&mut dyn Strategy; 4]) -> Result<RoundResult, EngineError> {
196        loop {
197            let Some(seat) = self.turn() else {
198                return Ok(self.round.result().expect("a turnless round is finished"));
199            };
200            if let Some(result) = self.step(&mut *strategies[seat as usize])? {
201                return Ok(result);
202            }
203        }
204    }
205}
206
207/// Play one round to completion, one strategy per seat, indexed by [`Seat`]
208///
209/// # Errors
210///
211/// [`EngineError::IllegalAction`] when a strategy's choice is rejected.
212pub fn play_round(
213    round: Round,
214    strategies: [&mut dyn Strategy; 4],
215) -> Result<RoundResult, EngineError> {
216    Table::new(round).play(strategies)
217}
218
219/// Deal and play rounds until the game is over, returning the settled score
220///
221/// # Errors
222///
223/// [`EngineError::IllegalAction`] when a strategy's choice is rejected.
224/// The game keeps the rounds recorded so far.
225#[cfg(feature = "rand")]
226pub fn play_game(
227    game: &mut hearts::Game,
228    strategies: [&mut dyn Strategy; 4],
229    rng: &mut (impl rand::Rng + ?Sized),
230) -> Result<hearts::FinalScore, EngineError> {
231    let [north, east, south, west] = strategies;
232    while !game.is_over() {
233        let mut table = Table::new(game.deal(rng)).scores(game.scores());
234        let result = table.play([&mut *north, &mut *east, &mut *south, &mut *west])?;
235        game.record(result)
236            .expect("a result produced by the round it was dealt for records cleanly");
237    }
238    Ok(game.final_score().expect("a game that is over settles"))
239}