hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
Documentation
//! Greedy bots play a full game of Hearts and narrate the score.
//!
//! Each bot passes its three highest cards and plays its lowest legal card
//! — no strategy, just legality; smarter play lives in the `hearts-engine`
//! crate.
//!
//! ```console
//! cargo run --features rand --example simulate
//! ```

use anyhow::{Context as _, Result};
use hearts::{Game, Hand, Phase, Round, Rules, Seat};

fn main() -> Result<()> {
    let mut rng = rand::rng();
    let mut game = Game::new(Rules::default());

    for number in 1.. {
        if game.is_over() {
            break;
        }

        let mut round = game.deal(&mut rng);
        play(&mut round)?;
        let result = round.result().context("the bots play every round out")?;

        game.record(result)?;
        print!("Round {number} ({}):", round.direction());
        for points in result.points() {
            print!(" {points:>2}");
        }
        if let Some(shooter) = result.shooter() {
            print!("  — {shooter} shoots the moon!");
        }
        println!();
    }

    let settled = game.final_score().context("the game just ended")?;
    println!();
    for seat in Seat::ALL {
        println!("{seat:>5}: {:>3}", settled.totals[seat as usize]);
    }
    let winners: Vec<String> = settled.winners().map(|seat| seat.to_string()).collect();
    println!(
        "{} win{}",
        winners.join(" and "),
        if winners.len() == 1 { "s" } else { "" }
    );
    Ok(())
}

/// Drive one round to completion with every seat played greedily.
fn play(round: &mut Round) -> Result<()> {
    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)?;
        }
    }

    while let Some(seat) = round.turn() {
        let lowest = round
            .legal_plays(seat)
            .into_iter()
            .next()
            .context("a live turn always has a legal play")?;
        round.play(seat, lowest)?;
    }
    Ok(())
}