use crate::{Strategy, View};
use hearts::round::RoundError;
use hearts::{Hand, Phase, Round, RoundResult, Seat};
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum EngineError {
#[error("{seat} chose an illegal action")]
IllegalAction {
seat: Seat,
#[source]
source: RoundError,
},
}
#[derive(Debug, Clone)]
pub struct Table {
round: Round,
voids: [u8; 4],
scores: [u16; 4],
}
fn infer_voids(round: &Round) -> [u8; 4] {
let mut voids = [0u8; 4];
for trick in round.tricks().iter().copied().chain(round.current_trick()) {
let Some(led) = trick.suit() else { continue };
for (seat, card) in trick.plays() {
if card.suit != led {
voids[seat as usize] |= 1 << led as u8;
}
}
}
voids
}
impl Table {
#[must_use]
pub fn new(round: Round) -> Self {
Self {
voids: infer_voids(&round),
round,
scores: [0; 4],
}
}
#[must_use]
pub const fn scores(mut self, scores: [u16; 4]) -> Self {
self.scores = scores;
self
}
#[cfg(feature = "rand")]
#[must_use]
pub fn deal(
rules: hearts::Rules,
direction: hearts::PassDirection,
rng: &mut (impl rand::Rng + ?Sized),
) -> Self {
Self::new(Round::deal(rules, direction, rng))
}
#[must_use]
pub const fn round(&self) -> &Round {
&self.round
}
#[must_use]
pub fn turn(&self) -> Option<Seat> {
match self.round.phase() {
Phase::Passing => Seat::ALL
.into_iter()
.find(|&seat| self.round.passed(seat).is_none()),
Phase::Playing => self.round.turn(),
Phase::Finished => None,
}
}
#[must_use]
pub fn points_settled(&self) -> bool {
self.round.phase() == Phase::Playing
&& Seat::ALL
.into_iter()
.map(|seat| u16::from(self.round.points_taken(seat)))
.sum::<u16>()
== 26
}
#[must_use]
pub const fn view(&self, seat: Seat) -> View<'_> {
let scores = [
self.scores[seat as usize],
self.scores[seat.left() as usize],
self.scores[seat.across() as usize],
self.scores[seat.right() as usize],
];
View::new(&self.round, seat, &self.voids, scores)
}
pub fn step(
&mut self,
strategy: &mut dyn Strategy,
) -> Result<Option<RoundResult>, EngineError> {
let Some(seat) = self.turn() else {
return Ok(self.round.result());
};
let reject = |source| EngineError::IllegalAction { seat, source };
match self.round.phase() {
Phase::Passing => {
let cards: Hand = strategy.pass_cards(&self.view(seat)).into_iter().collect();
self.round.pass(seat, cards).map_err(reject)?;
}
Phase::Playing => {
let card = strategy.play_card(&self.view(seat));
let led = self.round.current_trick().and_then(|trick| trick.suit());
self.round.play(seat, card).map_err(reject)?;
if let Some(led) = led
&& card.suit != led
{
self.voids[seat as usize] |= 1 << led as u8;
}
}
Phase::Finished => {}
}
Ok(self.round.result())
}
pub fn play(&mut self, strategies: [&mut dyn Strategy; 4]) -> Result<RoundResult, EngineError> {
loop {
let Some(seat) = self.turn() else {
return Ok(self.round.result().expect("a turnless round is finished"));
};
if let Some(result) = self.step(&mut *strategies[seat as usize])? {
return Ok(result);
}
}
}
}
pub fn play_round(
round: Round,
strategies: [&mut dyn Strategy; 4],
) -> Result<RoundResult, EngineError> {
Table::new(round).play(strategies)
}
#[cfg(feature = "rand")]
pub fn play_game(
game: &mut hearts::Game,
strategies: [&mut dyn Strategy; 4],
rng: &mut (impl rand::Rng + ?Sized),
) -> Result<hearts::FinalScore, EngineError> {
let [north, east, south, west] = strategies;
while !game.is_over() {
let mut table = Table::new(game.deal(rng)).scores(game.scores());
let result = table.play([&mut *north, &mut *east, &mut *south, &mut *west])?;
game.record(result)
.expect("a result produced by the round it was dealt for records cleanly");
}
Ok(game.final_score().expect("a game that is over settles"))
}