hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
Documentation

Hearts

Crates.io Docs.rs Build Status

This crate models the mechanics of Hearts: strongly typed cards and tricks, and a rules-driven state machine for complete four-player rounds and games — passing, the 2♣ opening, following suit, breaking hearts, and shooting the moon.

Hearts ranks the ace HIGH: the A♥ beats the K♥. Rank therefore encodes 2 = 2 through A = 14, matching crates for ace-high games such as contract-bridge and unlike the ace-low gin-rummy; these crates share patterns, never code.

Hands are written as four dot-separated suit groups in ascending order, clubs first: "23A.456.789.T" holds ♣2 ♣3 ♣A ♦4 ♦5 ♦6 ♥7 ♥8 ♥9 ♠10.

Modules

Feature flags

  • rand: shuffled dealing (Deck, Round::deal, Game::deal)
  • serde: serialization for the game-state types (cards, hands, seats, tricks, rounds, results, games); a mid-game Round snapshot is validated on deserialization by replaying its recorded history through the state machine

Quick start

Playing a fixed deal needs no features:

use hearts::{Hand, PassDirection, Round, Rules};

// The sorted deck dealt round-robin; a hold deal skips the passing phase.
let mut hands = [Hand::EMPTY; 4];
for (i, card) in Hand::ALL.into_iter().enumerate() {
    hands[i % 4].insert(card);
}

let mut round = Round::from_deal(Rules::new(), PassDirection::Hold, hands)?;
while let Some(seat) = round.turn() {
    let lowest = round.legal_plays(seat).into_iter().next().unwrap();
    round.play(seat, lowest)?;
}

let result = round.result().unwrap();
assert_eq!(result.points().iter().map(|&p| u32::from(p)).sum::<u32>(), 26);
# Ok::<(), Box<dyn std::error::Error>>(())

A complete bot-vs-bot game with the rand feature:

# #[cfg(feature = "rand")]
# fn main() {
use hearts::{Game, Hand, Phase, Rules, Seat};

let mut game = Game::new(Rules::default());
while !game.is_over() {
    let mut round = game.deal(&mut rand::rng());
    if round.phase() == Phase::Passing {
        for seat in Seat::ALL {
            let highest: Hand = round.hand(seat).into_iter().rev().take(3).collect();
            round.pass(seat, highest).unwrap();
        }
    }
    while let Some(seat) = round.turn() {
        let lowest = round.legal_plays(seat).into_iter().next().unwrap();
        round.play(seat, lowest).unwrap();
    }
    game.record(round.result().expect("round finished")).unwrap();
}
println!("{:?}", game.final_score());
# }
# #[cfg(not(feature = "rand"))]
# fn main() {}

Examples

  • playout: narrate one fixed deal — cargo run --example playout
  • simulate: greedy bots play a full game — cargo run --features rand --example simulate