hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
Documentation
//! The scoreboard across deals.
//!
//! A [`Game`] accumulates [`RoundResult`]s — pricing each moon as it lands —
//! until a seat reaches the game target.  The *lowest* total then wins;
//! equal lowest totals share the victory.  It also tracks the pass-direction
//! rotation: left, right, across, hold, repeating.

use crate::Rules;
use crate::round::RoundResult;
use crate::seat::{PassDirection, Seat};
use thiserror::Error;

/// Error returned when recording into a finished [`Game`]
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum GameError {
    /// The game is already over
    #[error("The game is already over")]
    AlreadyOver,
}

/// The settled outcome of a [`Game`]
///
/// Hearts is lowest-total-wins, and ties share the victory; ask
/// [`winners`](FinalScore::winners) for the champions and
/// [`winner`](FinalScore::winner) when you need a unique one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct FinalScore {
    /// Final totals by seat
    pub totals: [u16; 4],
}

impl FinalScore {
    /// The seats with the lowest total, sharing the victory
    pub fn winners(&self) -> impl Iterator<Item = Seat> + '_ {
        let min = *self.totals.iter().min().expect("four totals");
        Seat::ALL
            .into_iter()
            .filter(move |&seat| self.totals[seat as usize] == min)
    }

    /// The unique winner, or `None` when the victory is shared
    #[must_use]
    pub fn winner(&self) -> Option<Seat> {
        let mut winners = self.winners();
        match (winners.next(), winners.next()) {
            (Some(seat), None) => Some(seat),
            _ => None,
        }
    }
}

/// A game of Hearts: the running scores across rounds
///
/// ```
/// use hearts::{Game, PassDirection, RoundResult, Rules, Seat};
///
/// let mut game = Game::new(Rules::default());
/// assert_eq!(game.next_direction(), PassDirection::Left);
///
/// game.record(RoundResult::new([13, 13, 0, 0]))?;
/// assert_eq!(game.score(Seat::North), 13);
/// assert_eq!(game.next_direction(), PassDirection::Right);
/// # Ok::<(), hearts::game::GameError>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Game {
    rules: Rules,
    scores: [u16; 4],
    deals: u32,
}

impl Game {
    /// Start a game with the given rules
    #[must_use]
    #[inline]
    pub const fn new(rules: Rules) -> Self {
        Self {
            rules,
            scores: [0; 4],
            deals: 0,
        }
    }

    /// The rules of this game
    #[must_use]
    #[inline]
    pub const fn rules(&self) -> &Rules {
        &self.rules
    }

    /// The running score of a seat
    #[must_use]
    #[inline]
    pub const fn score(&self, seat: Seat) -> u16 {
        self.scores[seat as usize]
    }

    /// The running scores by seat
    #[must_use]
    #[inline]
    pub const fn scores(&self) -> [u16; 4] {
        self.scores
    }

    /// The number of rounds recorded so far
    #[must_use]
    #[inline]
    pub const fn deals(&self) -> u32 {
        self.deals
    }

    /// The pass direction of the next round under the standard rotation
    #[must_use]
    #[inline]
    pub const fn next_direction(&self) -> PassDirection {
        PassDirection::from_deal_index(self.deals)
    }

    /// Whether a seat has reached the game target
    #[must_use]
    pub const fn is_over(&self) -> bool {
        let target = self.rules.game_target;
        self.scores[0] >= target
            || self.scores[1] >= target
            || self.scores[2] >= target
            || self.scores[3] >= target
    }

    /// Record a finished round
    ///
    /// Each seat is charged the result's [`scores`](RoundResult::scores) —
    /// moon already priced — and the pass rotation advances.
    ///
    /// # Errors
    ///
    /// [`GameError::AlreadyOver`] once a seat has reached the target.
    pub fn record(&mut self, result: RoundResult) -> Result<(), GameError> {
        if self.is_over() {
            return Err(GameError::AlreadyOver);
        }

        let scores = result.scores(&self.rules);
        for seat in Seat::ALL {
            // Saturating: a total pinned at u16::MAX has long crossed any
            // target, so the game still ends correctly.
            let total = &mut self.scores[seat as usize];
            *total = total.saturating_add(scores[seat as usize]);
        }
        self.deals += 1;
        Ok(())
    }

    /// Shuffle and deal the next round with this game's rules and direction
    #[cfg(feature = "rand")]
    #[must_use]
    pub fn deal(&self, rng: &mut (impl rand::Rng + ?Sized)) -> crate::Round {
        crate::Round::deal(self.rules, self.next_direction(), rng)
    }

    /// Settle the game, or `None` while it is in play
    ///
    /// The lowest total wins; equal lowest totals share the victory.
    #[must_use]
    pub const fn final_score(&self) -> Option<FinalScore> {
        if self.is_over() {
            Some(FinalScore {
                totals: self.scores,
            })
        } else {
            None
        }
    }
}