use crate::hand::{Card, Hand};
use crate::seat::{PassDirection, Seat};
use crate::trick::Trick;
use crate::{Rules, Suit};
use core::fmt;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Phase {
Passing,
Playing,
Finished,
}
impl fmt::Display for Phase {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Passing => "passing",
Self::Playing => "playing",
Self::Finished => "finished",
})
}
}
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[error("Round points must sum to 26 with at least 13 for the Q♠ taker")]
pub struct InvalidResult(pub [u8; 4]);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(try_from = "[u8; 4]", into = "[u8; 4]")
)]
pub struct RoundResult {
points: [u8; 4],
}
impl RoundResult {
#[must_use]
#[inline]
pub const fn new(points: [u8; 4]) -> Self {
match Self::try_new(points) {
Ok(result) => result,
Err(_) => panic!("round points must sum to 26 with at least 13 for the Q♠ taker"),
}
}
#[inline]
pub const fn try_new(points: [u8; 4]) -> Result<Self, InvalidResult> {
let sum = points[0] as u16 + points[1] as u16 + points[2] as u16 + points[3] as u16;
let max = {
let ab = if points[0] > points[1] {
points[0]
} else {
points[1]
};
let cd = if points[2] > points[3] {
points[2]
} else {
points[3]
};
if ab > cd { ab } else { cd }
};
if sum == 26 && max >= 13 {
Ok(Self { points })
} else {
Err(InvalidResult(points))
}
}
#[must_use]
#[inline]
pub const fn points(self) -> [u8; 4] {
self.points
}
#[must_use]
pub fn shooter(self) -> Option<Seat> {
Seat::ALL
.into_iter()
.find(|&s| self.points[s as usize] == 26)
}
#[must_use]
pub fn scores(self, _rules: &Rules) -> [u16; 4] {
match self.shooter() {
Some(shooter) => {
let mut scores = [26; 4];
scores[shooter as usize] = 0;
scores
}
None => self.points.map(u16::from),
}
}
}
impl From<RoundResult> for [u8; 4] {
#[inline]
fn from(result: RoundResult) -> Self {
result.points
}
}
impl TryFrom<[u8; 4]> for RoundResult {
type Error = InvalidResult;
#[inline]
fn try_from(points: [u8; 4]) -> Result<Self, InvalidResult> {
Self::try_new(points)
}
}
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DealError {
#[error("Each seat is dealt exactly 13 cards")]
WrongHandSize,
#[error("A card appears in more than one hand")]
RepeatedCard,
#[error("A hand holds a bit that is not a card")]
UnknownCard,
}
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RoundError {
#[error("This action is not available in the {0} phase")]
WrongPhase(Phase),
#[error("It is not {0}'s turn")]
NotYourTurn(Seat),
#[error("{0} has already passed")]
AlreadyPassed(Seat),
#[error("A pass is exactly 3 cards, not {0}")]
WrongPassCount(usize),
#[error("{0} is not in the hand")]
NotInHand(Card),
#[error("The first trick is led with the 2♣")]
MustLeadTwoOfClubs,
#[error("The led suit {0} must be followed")]
MustFollowSuit(Suit),
#[error("Hearts cannot be led until a heart has been played")]
HeartsNotBroken,
#[error("{0} cannot be played on the first trick")]
FirstTrickPenalty(Card),
#[error("The card set holds a bit that is not a card")]
UnknownCard,
}
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(into = "repr::RoundRepr", try_from = "repr::RoundRepr")
)]
pub struct Round {
rules: Rules,
direction: PassDirection,
hands: [Hand; 4],
passes: [Option<Hand>; 4],
phase: Phase,
current: Option<Trick>,
tricks: Vec<Trick>,
result: Option<RoundResult>,
}
impl Clone for Round {
fn clone(&self) -> Self {
Self {
rules: self.rules,
direction: self.direction,
hands: self.hands,
passes: self.passes,
phase: self.phase,
current: self.current,
tricks: self.tricks.clone(),
result: self.result,
}
}
fn clone_from(&mut self, source: &Self) {
self.rules = source.rules;
self.direction = source.direction;
self.hands = source.hands;
self.passes = source.passes;
self.phase = source.phase;
self.current = source.current;
self.tricks.clone_from(&source.tricks);
self.result = source.result;
}
}
fn opening_leader(hands: &[Hand; 4]) -> Seat {
Seat::ALL
.into_iter()
.find(|&seat| hands[seat as usize].contains(Card::TWO_OF_CLUBS))
.expect("the four hands partition the deck, so one holds the 2♣")
}
impl Round {
pub fn from_deal(
rules: Rules,
direction: PassDirection,
hands: [Hand; 4],
) -> Result<Self, DealError> {
let mut seen = Hand::EMPTY;
for hand in hands {
if hand.len() != 13 {
return Err(DealError::WrongHandSize);
}
if !(seen & hand).is_empty() {
return Err(DealError::RepeatedCard);
}
seen |= hand;
}
if seen != Hand::ALL {
return Err(DealError::UnknownCard);
}
let passing = !matches!(direction, PassDirection::Hold);
Ok(Self {
rules,
direction,
passes: [None; 4],
phase: if passing {
Phase::Passing
} else {
Phase::Playing
},
current: if passing {
None
} else {
Some(Trick::new(opening_leader(&hands)))
},
hands,
tricks: Vec::with_capacity(13),
result: None,
})
}
#[allow(clippy::missing_panics_doc)]
#[cfg(feature = "rand")]
#[must_use]
pub fn deal(
rules: Rules,
direction: PassDirection,
rng: &mut (impl rand::Rng + ?Sized),
) -> Self {
let mut deck = crate::deck::Deck::ALL;
let hands = [
deck.draw(rng, 13),
deck.draw(rng, 13),
deck.draw(rng, 13),
deck.take(),
];
Self::from_deal(rules, direction, hands).expect("a fresh deck deals disjoint cards")
}
#[must_use]
#[inline]
pub const fn rules(&self) -> &Rules {
&self.rules
}
#[must_use]
#[inline]
pub const fn direction(&self) -> PassDirection {
self.direction
}
#[must_use]
#[inline]
pub const fn phase(&self) -> Phase {
self.phase
}
#[must_use]
#[inline]
pub const fn hand(&self, seat: Seat) -> Hand {
self.hands[seat as usize]
}
#[must_use]
#[inline]
pub const fn passed(&self, seat: Seat) -> Option<Hand> {
self.passes[seat as usize]
}
#[must_use]
#[inline]
pub const fn current_trick(&self) -> Option<Trick> {
self.current
}
#[must_use]
#[inline]
pub fn tricks(&self) -> &[Trick] {
&self.tricks
}
#[must_use]
pub fn turn(&self) -> Option<Seat> {
self.current.and_then(Trick::current)
}
#[must_use]
pub fn played(&self) -> Hand {
let tricks = self
.tricks
.iter()
.fold(Hand::EMPTY, |acc, t| acc | t.cards());
self.current.map_or(tricks, |t| tricks | t.cards())
}
#[must_use]
pub fn hearts_broken(&self) -> bool {
self.tricks
.iter()
.copied()
.chain(self.current)
.any(|trick| trick.plays().any(|(_, card)| card.suit == Suit::Hearts))
}
#[must_use]
pub fn taken(&self, seat: Seat) -> Hand {
self.tricks
.iter()
.filter(|t| t.winner() == Some(seat))
.fold(Hand::EMPTY, |acc, t| acc | t.cards())
}
#[must_use]
pub fn points_taken(&self, seat: Seat) -> u8 {
self.taken(seat).points()
}
#[must_use]
#[inline]
pub const fn result(&self) -> Option<RoundResult> {
self.result
}
const fn expect_phase(&self, phase: Phase) -> Result<(), RoundError> {
if self.phase as u8 == phase as u8 {
Ok(())
} else {
Err(RoundError::WrongPhase(self.phase))
}
}
#[must_use]
pub fn legal_plays(&self, seat: Seat) -> Hand {
fn or_else(preferred: Hand, fallback: Hand) -> Hand {
if preferred.is_empty() {
fallback
} else {
preferred
}
}
let Some(trick) = self.current else {
return Hand::EMPTY;
};
if trick.current() != Some(seat) {
return Hand::EMPTY;
}
let hand = self.hands[seat as usize];
match trick.suit() {
None => {
if self.tricks.is_empty() {
Hand::TWO_OF_CLUBS
} else if self.hearts_broken() {
hand
} else {
or_else(hand - Hand::HEARTS, hand)
}
}
Some(led) => {
let mut follow = Hand::EMPTY;
follow[led] = hand[led];
if !follow.is_empty() {
follow
} else if self.tricks.is_empty() {
or_else(hand - Hand::PENALTIES, hand)
} else {
hand
}
}
}
}
pub fn pass(&mut self, seat: Seat, cards: Hand) -> Result<(), RoundError> {
self.expect_phase(Phase::Passing)?;
if self.passes[seat as usize].is_some() {
return Err(RoundError::AlreadyPassed(seat));
}
if cards.contains_unknown_bits() {
return Err(RoundError::UnknownCard);
}
if cards.len() != 3 {
return Err(RoundError::WrongPassCount(cards.len()));
}
if let Some(card) = (cards - self.hands[seat as usize]).into_iter().next() {
return Err(RoundError::NotInHand(card));
}
self.hands[seat as usize] -= cards;
self.passes[seat as usize] = Some(cards);
if self.passes.iter().all(Option::is_some) {
for giver in Seat::ALL {
if let Some(passed) = self.passes[giver as usize] {
self.hands[self.direction.receiver(giver) as usize] |= passed;
}
}
self.phase = Phase::Playing;
self.current = Some(Trick::new(opening_leader(&self.hands)));
}
Ok(())
}
#[allow(clippy::missing_panics_doc)]
pub fn play(&mut self, seat: Seat, card: Card) -> Result<(), RoundError> {
self.expect_phase(Phase::Playing)?;
let mut trick = self.current.expect("a playing round has a live trick");
if trick.current() != Some(seat) {
return Err(RoundError::NotYourTurn(seat));
}
let hand = self.hands[seat as usize];
if !hand.contains(card) {
return Err(RoundError::NotInHand(card));
}
let first = self.tricks.is_empty();
match trick.suit() {
None => {
if first && card != Card::TWO_OF_CLUBS {
return Err(RoundError::MustLeadTwoOfClubs);
}
if card.suit == Suit::Hearts
&& !self.hearts_broken()
&& !(hand - Hand::HEARTS).is_empty()
{
return Err(RoundError::HeartsNotBroken);
}
}
Some(led) => {
if card.suit != led && !hand[led].is_empty() {
return Err(RoundError::MustFollowSuit(led));
}
if first && card.points() > 0 && !(hand - Hand::PENALTIES).is_empty() {
return Err(RoundError::FirstTrickPenalty(card));
}
}
}
self.hands[seat as usize].remove(card);
trick
.play(card)
.expect("the current trick is never complete");
if trick.is_complete() {
let winner = trick.winner().expect("a complete trick has a winner");
self.tricks.push(trick);
if self.tricks.len() == 13 {
let mut points = [0u8; 4];
for taken in &self.tricks {
let winner = taken.winner().expect("a complete trick has a winner");
points[winner as usize] += taken.points();
}
self.current = None;
self.phase = Phase::Finished;
self.result =
Some(RoundResult::try_new(points).expect("thirteen tricks tally 26 points"));
} else {
self.current = Some(Trick::new(winner));
}
} else {
self.current = Some(trick);
}
Ok(())
}
}
#[cfg(feature = "serde")]
mod repr {
use super::{DealError, Phase, Round, RoundError, RoundResult};
use crate::Rules;
use crate::hand::Hand;
use crate::seat::{PassDirection, Seat};
use crate::trick::Trick;
use thiserror::Error;
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidRound {
#[error("The snapshot does not reconstruct a legal deal: {0}")]
Deal(#[from] DealError),
#[error("The recorded history is not a legal sequence of actions: {0}")]
History(#[from] RoundError),
#[error("The snapshot does not match its replayed history")]
Mismatch,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct RoundRepr {
rules: Rules,
direction: PassDirection,
hands: [Hand; 4],
passes: [Option<Hand>; 4],
phase: Phase,
current: Option<Trick>,
tricks: Vec<Trick>,
result: Option<RoundResult>,
}
impl From<Round> for RoundRepr {
fn from(round: Round) -> Self {
Self {
rules: round.rules,
direction: round.direction,
hands: round.hands,
passes: round.passes,
phase: round.phase,
current: round.current,
tricks: round.tricks,
result: round.result,
}
}
}
impl RoundRepr {
fn history(&self) -> impl Iterator<Item = &Trick> {
self.tricks.iter().chain(&self.current)
}
fn pre_pass_hands(&self) -> [Hand; 4] {
let mut played = [Hand::EMPTY; 4];
for trick in self.history() {
for (seat, card) in trick.plays() {
played[seat as usize].insert(card);
}
}
Seat::ALL.map(|seat| {
let passed = self.passes[seat as usize].unwrap_or(Hand::EMPTY);
let giver = self.direction.giver(seat);
let received = self.passes[giver as usize].unwrap_or(Hand::EMPTY);
(self.hands[seat as usize] | played[seat as usize] | passed) - received
})
}
}
impl TryFrom<RoundRepr> for Round {
type Error = InvalidRound;
fn try_from(repr: RoundRepr) -> Result<Self, InvalidRound> {
let mut round = Round::from_deal(repr.rules, repr.direction, repr.pre_pass_hands())?;
for seat in Seat::ALL {
if let Some(cards) = repr.passes[seat as usize] {
round.pass(seat, cards)?;
}
}
for trick in repr.history() {
for (seat, card) in trick.plays() {
round.play(seat, card)?;
}
}
if round.hands != repr.hands
|| round.phase != repr.phase
|| round.current != repr.current
|| round.tricks != repr.tricks
|| round.result != repr.result
{
return Err(InvalidRound::Mismatch);
}
Ok(round)
}
}
}
#[cfg(feature = "serde")]
pub use repr::InvalidRound;