hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
Documentation
//! A single trick: four cards in play order.
//!
//! [`Trick`] is a dumb container — it records who led and what was played,
//! in order, and answers questions about the cards ([`suit`](Trick::suit),
//! [`winner`](Trick::winner), [`points`](Trick::points)).  Whether a play is
//! *legal* is the business of [`Round`](crate::round::Round); the only error
//! a trick itself can raise is [`TrickFull`].

use crate::Suit;
use crate::hand::{Card, Hand};
use crate::seat::Seat;
use core::fmt;
use thiserror::Error;

/// Error returned when playing to a trick that already has four cards
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[error("The trick already has four cards")]
pub struct TrickFull;

/// A trick in progress or completed
///
/// Cards are stored in play order: the leader's card first, then clockwise.
/// The trick is won by the highest card of the led suit — there are no
/// trumps in Hearts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(into = "repr::TrickRepr", try_from = "repr::TrickRepr")
)]
pub struct Trick {
    leader: Seat,
    cards: [Option<Card>; 4],
}

impl Trick {
    /// An empty trick led by `leader`
    #[must_use]
    #[inline]
    pub const fn new(leader: Seat) -> Self {
        Self {
            leader,
            cards: [None; 4],
        }
    }

    /// The seat that led (or is to lead) this trick
    #[must_use]
    #[inline]
    pub const fn leader(self) -> Seat {
        self.leader
    }

    /// The number of cards played so far
    #[must_use]
    #[inline]
    pub fn len(self) -> usize {
        self.cards.iter().flatten().count()
    }

    /// Whether the trick has no cards yet
    #[must_use]
    #[inline]
    pub fn is_empty(self) -> bool {
        self.cards[0].is_none()
    }

    /// Whether all four cards have been played
    #[must_use]
    #[inline]
    pub fn is_complete(self) -> bool {
        self.cards[3].is_some()
    }

    /// The led suit, or `None` if no card has been played
    #[must_use]
    #[inline]
    pub fn suit(self) -> Option<Suit> {
        self.cards[0].map(|card| card.suit)
    }

    /// The seat to play next, or `None` if the trick is complete
    #[must_use]
    pub fn current(self) -> Option<Seat> {
        let mut seat = self.leader;
        for card in self.cards {
            if card.is_none() {
                return Some(seat);
            }
            seat = seat.left();
        }
        None
    }

    /// The card played by `seat`, or `None` if it has not played yet
    #[must_use]
    pub fn card_from(self, seat: Seat) -> Option<Card> {
        self.plays().find(|&(s, _)| s == seat).map(|(_, card)| card)
    }

    /// Append a card in play order
    ///
    /// The trick does not judge legality; see
    /// [`Round::play`](crate::round::Round::play) for the rules.
    ///
    /// # Errors
    ///
    /// [`TrickFull`] when four cards have already been played.
    pub fn play(&mut self, card: Card) -> Result<(), TrickFull> {
        let slot = self
            .cards
            .iter_mut()
            .find(|c| c.is_none())
            .ok_or(TrickFull)?;
        *slot = Some(card);
        Ok(())
    }

    /// The seat currently winning: the highest card of the led suit
    ///
    /// `None` only for an empty trick.  On a complete trick this is the
    /// winner, who takes the cards and leads the next trick.
    #[must_use]
    pub fn winner(self) -> Option<Seat> {
        let suit = self.suit()?;
        self.plays()
            .filter(|(_, card)| card.suit == suit)
            .max_by_key(|(_, card)| card.rank)
            .map(|(seat, _)| seat)
    }

    /// The set of cards played to this trick
    #[must_use]
    pub fn cards(self) -> Hand {
        self.cards.iter().flatten().copied().collect()
    }

    /// Penalty points in this trick: 1 per heart, 13 for Q♠
    #[must_use]
    pub fn points(self) -> u8 {
        self.cards().points()
    }

    /// Iterate over `(seat, card)` in play order
    pub fn plays(self) -> impl Iterator<Item = (Seat, Card)> {
        let mut seat = self.leader;
        self.cards.into_iter().flatten().map(move |card| {
            let play = (seat, card);
            seat = seat.left();
            play
        })
    }
}

/// Plays in order as `Seat:Card` pairs, e.g. `N:2♣ E:5♣ S:K♣ W:A♣`
///
/// An empty trick shows only the leader, e.g. `N:`.
impl fmt::Display for Trick {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            return write!(f, "{}:", self.leader.letter());
        }
        for (i, (seat, card)) in self.plays().enumerate() {
            if i > 0 {
                f.write_str(" ")?;
            }
            write!(f, "{}:{card}", seat.letter())?;
        }
        Ok(())
    }
}

/// The serialized form of a [`Trick`], validated on deserialization
///
/// [`Trick::play`] always fills the first empty slot, so a genuine trick's
/// cards are a contiguous, duplicate-free prefix; a snapshot violating that
/// would silently misattribute plays to seats.
#[cfg(feature = "serde")]
mod repr {
    use super::Trick;
    use crate::hand::{Card, Hand};
    use crate::seat::Seat;
    use thiserror::Error;

    /// Error rejecting a corrupt [`Trick`](super::Trick) snapshot
    #[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
    #[error("Trick cards must fill a contiguous prefix of distinct cards")]
    pub struct InvalidTrick;

    #[derive(Clone, Copy, serde::Serialize, serde::Deserialize)]
    pub struct TrickRepr {
        leader: Seat,
        cards: [Option<Card>; 4],
    }

    impl From<Trick> for TrickRepr {
        fn from(trick: Trick) -> Self {
            Self {
                leader: trick.leader,
                cards: trick.cards,
            }
        }
    }

    impl TryFrom<TrickRepr> for Trick {
        type Error = InvalidTrick;

        fn try_from(repr: TrickRepr) -> Result<Self, InvalidTrick> {
            let contiguous = repr
                .cards
                .windows(2)
                .all(|pair| pair[0].is_some() || pair[1].is_none());
            let played: Hand = repr.cards.iter().flatten().copied().collect();
            if contiguous && played.len() == repr.cards.iter().flatten().count() {
                Ok(Self {
                    leader: repr.leader,
                    cards: repr.cards,
                })
            } else {
                Err(InvalidTrick)
            }
        }
    }
}

#[cfg(feature = "serde")]
pub use repr::InvalidTrick;

#[cfg(test)]
mod tests {
    use super::*;

    fn card(s: &str) -> Card {
        s.parse().unwrap()
    }

    #[test]
    fn play_order_and_winner() {
        let mut trick = Trick::new(Seat::West);
        assert!(trick.is_empty());
        assert_eq!(trick.current(), Some(Seat::West));
        assert_eq!(trick.winner(), None);
        assert_eq!(trick.suit(), None);

        trick.play(card("2♣")).unwrap();
        assert_eq!(trick.suit(), Some(Suit::Clubs));
        assert_eq!(trick.current(), Some(Seat::North));
        assert_eq!(trick.winner(), Some(Seat::West));

        trick.play(card("A♥")).unwrap();
        // The off-suit ace does not win.
        assert_eq!(trick.winner(), Some(Seat::West));

        trick.play(card("T♣")).unwrap();
        assert_eq!(trick.winner(), Some(Seat::East));
        assert!(!trick.is_complete());

        trick.play(card("Q♠")).unwrap();
        assert!(trick.is_complete());
        assert_eq!(trick.current(), None);
        assert_eq!(trick.winner(), Some(Seat::East));
        assert_eq!(trick.play(card("3♣")), Err(TrickFull));

        assert_eq!(trick.len(), 4);
        assert_eq!(trick.points(), 14);
        assert_eq!(trick.card_from(Seat::North), Some(card("A♥")));
        assert_eq!(trick.cards().len(), 4);
        assert_eq!(trick.to_string(), "W:2♣ N:A♥ E:T♣ S:Q♠");
    }

    #[test]
    fn led_suit_max_wins() {
        let mut trick = Trick::new(Seat::North);
        for text in ["5♦", "K♦", "A♦", "6♦"] {
            trick.play(card(text)).unwrap();
        }
        assert_eq!(trick.winner(), Some(Seat::South));
        assert_eq!(trick.points(), 0);
    }
}