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(())
}
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(())
}