From 97d685af60a113b1bee15eaf4ec80101d40a4171 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 11:48:44 +0100 Subject: [PATCH] Add hand evaluation and Monte Carlo equity Co-Authored-By: Claude Opus 5.5 --- src/equity/mod.rs | 4 + src/equity/monte_carlo.rs | 73 ++++++++++++++++- src/equity/outcome.rs | 19 +++++ src/equity/sample.rs | 33 ++++++++ src/equity/tally.rs | 44 +++++++++++ src/equity/validate.rs | 51 ++++++++++++ src/hand/category.rs | 13 +++ src/hand/five.rs | 68 ++++++++++++++++ src/hand/mod.rs | 6 ++ src/hand/showdown.rs | 56 +++++++++++++ src/hand/strength.rs | 10 +++ src/hand/subset.rs | 19 +++++ tests/equity_faults.rs | 83 +++++++++++++++++++ tests/equity_properties.rs | 153 +++++++++++++++++++++++++++++++++++ tests/equity_reference.rs | 158 +++++++++++++++++++++++++++++++++++++ tests/hand_five_cards.rs | 117 +++++++++++++++++++++++++++ tests/hand_showdown.rs | 116 +++++++++++++++++++++++++++ 17 files changed, 1021 insertions(+), 2 deletions(-) create mode 100644 src/equity/outcome.rs create mode 100644 src/equity/sample.rs create mode 100644 src/equity/tally.rs create mode 100644 src/equity/validate.rs create mode 100644 src/hand/category.rs create mode 100644 src/hand/five.rs create mode 100644 src/hand/showdown.rs create mode 100644 src/hand/strength.rs create mode 100644 src/hand/subset.rs create mode 100644 tests/equity_faults.rs create mode 100644 tests/equity_properties.rs create mode 100644 tests/equity_reference.rs create mode 100644 tests/hand_five_cards.rs create mode 100644 tests/hand_showdown.rs diff --git a/src/equity/mod.rs b/src/equity/mod.rs index b0d0b348..59502954 100644 --- a/src/equity/mod.rs +++ b/src/equity/mod.rs @@ -2,5 +2,9 @@ pub mod estimate; pub mod monte_carlo; +pub mod outcome; pub mod query; +pub mod sample; +pub mod tally; +pub mod validate; pub mod villain_range; diff --git a/src/equity/monte_carlo.rs b/src/equity/monte_carlo.rs index 8a5ebd88..ea0023fe 100644 --- a/src/equity/monte_carlo.rs +++ b/src/equity/monte_carlo.rs @@ -1,10 +1,79 @@ use super::estimate::Estimate; +use super::outcome::Outcome; use super::query::Query; +use super::sample::{deal, shuffle_front}; +use super::tally::Tally; +use super::validate::remaining_deck; +use super::villain_range::VillainRange; +use crate::card::Card; use crate::fault::Fault; +use crate::hand::showdown::best; use crate::rng::Rng; /// Seeded Monte Carlo equity. Same query + same rng ⇒ same estimate. +/// +/// `Filter` ranges are sampled by bounded rejection (see `sample::deal` for the fallback). pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { - let _ = (query, rng); - todo!("equity::monte_carlo") + let mut pool = remaining_deck(query)?; + let (tally, rng) = (0..query.trials).try_fold((Tally::default(), rng), |(tally, rng), _| { + let (outcome, rng) = play_trial(query, &mut pool, rng)?; + Ok::<_, Fault>((tally.record(outcome), rng)) + })?; + Ok((tally.finish(), rng)) +} + +/// One deal: villain hands first (in query order), then the rest of the board. +fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rng), Fault> { + let k = query.rules.hole_cards; + let usage = query.rules.hole_usage; + let accept_all = |_: &[Card]| true; + let mut front = 0; + let mut rng = rng; + // Where each villain's cards live: Some(start in pool) for sampled hands. + let mut starts: Vec> = Vec::with_capacity(query.villains.len()); + for villain in query.villains { + match villain { + VillainRange::Exact(_) => starts.push(None), + VillainRange::Any => { + rng = deal(pool, front, k, &accept_all, rng); + starts.push(Some(front)); + front += k; + } + VillainRange::Filter(accept) => { + rng = deal(pool, front, k, *accept, rng); + starts.push(Some(front)); + front += k; + } + } + } + let missing = 5 - query.board.len(); + rng = shuffle_front(pool, front, missing, rng); + let mut board = [query.hero[0]; 5]; + query.board.iter().chain(&pool[front..front + missing]).enumerate().for_each(|(i, c)| board[i] = *c); + + let hero = best(usage, query.hero, &board)?; + let mut rivals_best = None; + let mut rivals_tied = 0u32; + for (villain, start) in query.villains.iter().zip(&starts) { + let hand: &[Card] = match (villain, start) { + (VillainRange::Exact(cards), _) => cards, + (_, Some(s)) => &pool[*s..*s + k], + (_, None) => &[], + }; + let strength = best(usage, hand, &board)?; + match rivals_best { + Some(top) if strength < top => {} + Some(top) if strength == top => rivals_tied += 1, + _ => { + rivals_best = Some(strength); + rivals_tied = 1; + } + } + } + let outcome = match rivals_best { + Some(top) if hero < top => Outcome::Loss, + Some(top) if hero == top => Outcome::Tie { ways: rivals_tied + 1 }, + _ => Outcome::Win, + }; + Ok((outcome, rng)) } diff --git a/src/equity/outcome.rs b/src/equity/outcome.rs new file mode 100644 index 00000000..197a72d0 --- /dev/null +++ b/src/equity/outcome.rs @@ -0,0 +1,19 @@ +/// How one simulated deal ended for hero. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Outcome { + Win, + /// Tie for the best hand; `ways` counts hero and every other tying player (>= 2). + Tie { ways: u32 }, + Loss, +} + +impl Outcome { + /// Hero's share of the pot in this deal. + pub fn share(self) -> f64 { + match self { + Outcome::Win => 1.0, + Outcome::Tie { ways } => 1.0 / ways.max(1) as f64, + Outcome::Loss => 0.0, + } + } +} diff --git a/src/equity/sample.rs b/src/equity/sample.rs new file mode 100644 index 00000000..76e39a33 --- /dev/null +++ b/src/equity/sample.rs @@ -0,0 +1,33 @@ +//! Dealing from a pool that is rearranged in place (private to one simulation run). +//! +//! The pool is only ever permuted, so any arrangement is a uniform starting point for the next +//! partial Fisher-Yates pass; the arrangement itself never leaks out of `monte_carlo`. + +use crate::card::Card; +use crate::rng::Rng; + +/// Attempts a `Filter` range gets per hand before the last sample is accepted unfiltered. +pub const MAX_FILTER_ATTEMPTS: u32 = 200; + +/// Moves `count` uniformly chosen cards from `pool[front..]` to `pool[front..front + count]`. +pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> Rng { + (0..count).fold(rng, |rng, i| { + let (offset, rng) = rng.below((pool.len() - front - i) as u64); + pool.swap(front + i, front + i + offset as usize); + rng + }) +} + +/// Deals `count` cards at `front`, re-sampling while `accept` refuses (bounded). +/// Fallback: after `MAX_FILTER_ATTEMPTS` refusals the last sample is kept, i.e. a range that +/// (almost) never matches degrades to a uniformly random hand instead of failing the run. +pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { + let mut rng = rng; + for _ in 0..MAX_FILTER_ATTEMPTS { + rng = shuffle_front(pool, front, count, rng); + if accept(&pool[front..front + count]) { + break; + } + } + rng +} diff --git a/src/equity/tally.rs b/src/equity/tally.rs new file mode 100644 index 00000000..f84f8c25 --- /dev/null +++ b/src/equity/tally.rs @@ -0,0 +1,44 @@ +//! Running sums over outcomes and their reduction to an `Estimate`. + +use super::estimate::Estimate; +use super::outcome::Outcome; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Tally { + trials: u32, + wins: u32, + ties: u32, + share_sum: f64, + share_square_sum: f64, +} + +impl Tally { + pub fn record(self, outcome: Outcome) -> Tally { + let share = outcome.share(); + Tally { + trials: self.trials + 1, + wins: self.wins + u32::from(outcome == Outcome::Win), + ties: self.ties + u32::from(matches!(outcome, Outcome::Tie { .. })), + share_sum: self.share_sum + share, + share_square_sum: self.share_square_sum + share * share, + } + } + + pub fn finish(self) -> Estimate { + let n = self.trials.max(1) as f64; + let share = self.share_sum / n; + // Unbiased sample variance of the per-trial share; the error of the mean is sqrt(var / n). + let variance = if self.trials > 1 { + ((self.share_square_sum - n * share * share) / (n - 1.0)).max(0.0) + } else { + 0.0 + }; + Estimate { + win: self.wins as f64 / n, + tie: self.ties as f64 / n, + share, + trials: self.trials, + std_error: (variance / n).sqrt(), + } + } +} diff --git a/src/equity/validate.rs b/src/equity/validate.rs new file mode 100644 index 00000000..05e082ff --- /dev/null +++ b/src/equity/validate.rs @@ -0,0 +1,51 @@ +//! Query checks. Everything that can make a simulation meaningless is a `Fault` here. + +use super::query::Query; +use super::villain_range::VillainRange; +use crate::card::{deck, Card}; +use crate::fault::Fault; + +fn invalid(field: &str, detail: String) -> Fault { + Fault::Invalid { field: field.into(), detail } +} + +/// Returns the cards still available for random dealing. +pub fn remaining_deck(query: &Query) -> Result, Fault> { + let k = query.rules.hole_cards; + if query.trials == 0 { + return Err(invalid("trials", "must be at least 1".into())); + } + if query.hero.len() != k { + return Err(invalid("hero", format!("expected {k} hole cards, got {}", query.hero.len()))); + } + if !matches!(query.board.len(), 0 | 3 | 4 | 5) { + return Err(invalid("board", format!("expected 0, 3, 4 or 5 cards, got {}", query.board.len()))); + } + let known = known_hands(query, k)?; + let dead: Vec = query.hero.iter().chain(query.board).chain(&known).copied().collect(); + if dead.iter().enumerate().any(|(i, c)| dead[..i].contains(c)) { + return Err(Fault::Inconsistent("a card appears more than once".into())); + } + let pool = deck::without(&dead); + let random = query.villains.iter().filter(|v| !matches!(v, VillainRange::Exact(_))).count(); + let needed = random * k + (5 - query.board.len()); + if needed > pool.len() { + return Err(Fault::Exhausted(format!("{needed} cards needed, {} left in the deck", pool.len()))); + } + Ok(pool) +} + +fn known_hands(query: &Query, k: usize) -> Result, Fault> { + let hands = query.villains.iter().filter_map(|v| match v { + VillainRange::Exact(cards) => Some(cards), + _ => None, + }); + hands.fold(Ok(Vec::new()), |acc, cards| { + let mut all = acc?; + if cards.len() != k { + return Err(invalid("villain", format!("expected {k} cards, got {}", cards.len()))); + } + all.extend_from_slice(cards); + Ok(all) + }) +} diff --git a/src/hand/category.rs b/src/hand/category.rs new file mode 100644 index 00000000..b7d4a08e --- /dev/null +++ b/src/hand/category.rs @@ -0,0 +1,13 @@ +/// Hand classes, weakest to strongest (the derived order is the poker order). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Category { + HighCard, + Pair, + TwoPair, + ThreeOfAKind, + Straight, + Flush, + FullHouse, + FourOfAKind, + StraightFlush, +} diff --git a/src/hand/five.rs b/src/hand/five.rs new file mode 100644 index 00000000..8997bee0 --- /dev/null +++ b/src/hand/five.rs @@ -0,0 +1,68 @@ +//! Exact evaluation of five cards. + +use super::category::Category; +use super::strength::Strength; +use crate::card::Card; + +pub fn evaluate(cards: &[Card; 5]) -> Strength { + let counts = rank_counts(cards); + let groups = groups_by_weight(&counts); + let flush = cards.iter().all(|c| c.suit == cards[0].suit); + let straight_high = straight_high(&groups); + let ranks = tie_break(&groups); + let category = match (straight_high, flush, groups[0].0, groups[1].0) { + (Some(_), true, _, _) => Category::StraightFlush, + (_, _, 4, _) => Category::FourOfAKind, + (_, _, 3, 2) => Category::FullHouse, + (_, true, _, _) => Category::Flush, + (Some(_), _, _, _) => Category::Straight, + (_, _, 3, _) => Category::ThreeOfAKind, + (_, _, 2, 2) => Category::TwoPair, + (_, _, 2, _) => Category::Pair, + _ => Category::HighCard, + }; + let ranks = match (category, straight_high) { + (Category::Straight | Category::StraightFlush, Some(high)) => [high, 0, 0, 0, 0], + _ => ranks, + }; + Strength { category, ranks } +} + +fn rank_counts(cards: &[Card; 5]) -> [u8; 15] { + let mut counts = [0u8; 15]; + cards.iter().for_each(|c| counts[c.rank.value() as usize] += 1); + counts +} + +/// `(count, rank)` pairs, most numerous first, then highest rank; unused slots `(0, 0)`. +fn groups_by_weight(counts: &[u8; 15]) -> [(u8, u8); 5] { + let mut groups = [(0u8, 0u8); 5]; + let mut filled = 0; + for rank in (2..=14u8).rev() { + let count = counts[rank as usize]; + if count > 0 { + groups[filled] = (count, rank); + filled += 1; + } + } + groups.sort_by(|a, b| b.cmp(a)); + groups +} + +fn tie_break(groups: &[(u8, u8); 5]) -> [u8; 5] { + let mut ranks = [0u8; 5]; + groups.iter().enumerate().for_each(|(i, g)| ranks[i] = g.1); + ranks +} + +/// High card of the straight when the five cards are five consecutive ranks (ace may be low). +fn straight_high(groups: &[(u8, u8); 5]) -> Option { + let distinct = groups.iter().all(|g| g.0 == 1); + let ranks = tie_break(groups); // descending because all counts are 1 + match (distinct, ranks) { + (false, _) => None, + (true, [14, 5, 4, 3, 2]) => Some(5), + (true, r) if r[0] - r[4] == 4 => Some(r[0]), + _ => None, + } +} diff --git a/src/hand/mod.rs b/src/hand/mod.rs index 44ee6cf9..19f7ece8 100644 --- a/src/hand/mod.rs +++ b/src/hand/mod.rs @@ -1 +1,7 @@ //! Hand evaluation: rank categories, comparable strengths, best-hand selection per variant. + +pub mod category; +pub mod five; +pub mod showdown; +pub mod strength; +pub mod subset; diff --git a/src/hand/showdown.rs b/src/hand/showdown.rs new file mode 100644 index 00000000..0134e92f --- /dev/null +++ b/src/hand/showdown.rs @@ -0,0 +1,56 @@ +//! Best hand for a player under the variant's hole-card usage rule. + +use super::five::evaluate; +use super::strength::Strength; +use super::subset::{masks, pick}; +use crate::card::Card; +use crate::fault::Fault; +use crate::variant::HoleUsage; + +/// Hold'em family: 5-7 cards in total. Omaha family: >= 2 hole and 3-5 board cards. +pub fn best(usage: HoleUsage, hole: &[Card], board: &[Card]) -> Result { + distinct(hole, board)?; + match usage { + HoleUsage::BestFiveOfAll => best_of_all(hole, board), + HoleUsage::ExactlyTwoHole => exactly_two(hole, board), + } +} + +fn invalid(detail: &str) -> Fault { + Fault::Invalid { field: "cards".into(), detail: detail.into() } +} + +fn distinct(hole: &[Card], board: &[Card]) -> Result<(), Fault> { + let all: Vec = hole.iter().chain(board).copied().collect(); + let repeated = all.iter().enumerate().any(|(i, c)| all[..i].contains(c)); + if repeated { + Err(Fault::Inconsistent("duplicate card".into())) + } else { + Ok(()) + } +} + +fn best_of_all(hole: &[Card], board: &[Card]) -> Result { + let all: Vec = hole.iter().chain(board).copied().collect(); + if !(5..=7).contains(&all.len()) || hole.is_empty() { + return Err(invalid("hold'em needs 5 to 7 cards including hole cards")); + } + masks(all.len(), 5) + .filter_map(|m| pick::<5>(&all, m)) + .map(|five| evaluate(&five)) + .max() + .ok_or_else(|| invalid("no five-card selection")) +} + +fn exactly_two(hole: &[Card], board: &[Card]) -> Result { + if hole.len() < 2 || hole.len() > 6 || !(3..=5).contains(&board.len()) { + return Err(invalid("omaha needs 2+ hole cards and 3 to 5 board cards")); + } + let boards: Vec<[Card; 3]> = masks(board.len(), 3).filter_map(|m| pick::<3>(board, m)).collect(); + masks(hole.len(), 2) + .filter_map(|m| pick::<2>(hole, m)) + .flat_map(|pair| boards.iter().map(move |b| [pair[0], pair[1], b[0], b[1], b[2]])) + .map(|five| evaluate(&five)) + .max() + .ok_or_else(|| invalid("no five-card selection")) +} diff --git a/src/hand/strength.rs b/src/hand/strength.rs new file mode 100644 index 00000000..2500939b --- /dev/null +++ b/src/hand/strength.rs @@ -0,0 +1,10 @@ +use super::category::Category; + +/// Totally ordered hand value: category first, then the tie-break ranks +/// (pip values, most significant first; unused slots are 0). +/// Equal strengths are split pots. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Strength { + pub category: Category, + pub ranks: [u8; 5], +} diff --git a/src/hand/subset.rs b/src/hand/subset.rs new file mode 100644 index 00000000..910b7b70 --- /dev/null +++ b/src/hand/subset.rs @@ -0,0 +1,19 @@ +//! Allocation-free enumeration of k-element subsets by bit mask (n <= 8 in practice). + +use crate::card::Card; + +/// All masks over `n` positions with exactly `k` bits set. +pub fn masks(n: usize, k: u32) -> impl Iterator { + (0u32..(1u32 << n)).filter(move |m| m.count_ones() == k) +} + +/// The cards selected by `mask`, packed into the front of a fixed array. +pub fn pick(cards: &[Card], mask: u32) -> Option<[Card; K]> { + let mut picked = cards.iter().enumerate().filter(|(i, _)| mask >> i & 1 == 1).map(|(_, c)| *c); + let first = *cards.first()?; + let mut out = [first; K]; + for slot in out.iter_mut() { + *slot = picked.next()?; + } + Some(out) +} diff --git a/tests/equity_faults.rs b/tests/equity_faults.rs new file mode 100644 index 00000000..5d8a614c --- /dev/null +++ b/tests/equity_faults.rs @@ -0,0 +1,83 @@ +//! Invalid queries are faults, never panics. +use pokerfreak::card::Card; +use pokerfreak::equity::monte_carlo::estimate; +use pokerfreak::equity::query::Query; +use pokerfreak::equity::villain_range::VillainRange; +use pokerfreak::fault::Fault; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{rules, Variant}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +fn fault(variant: Variant, hero: &str, board: &str, villains: &[VillainRange], trials: u32) -> Fault { + let (hero, board) = (cs(hero), cs(board)); + let query = Query { rules: rules(variant), hero: &hero, board: &board, villains, trials }; + estimate(&query, Rng::seeded(1)).expect_err("expected a fault") +} + +const ANY: [VillainRange; 1] = [VillainRange::Any]; + +#[test] +fn wrong_hero_card_count_is_invalid() { + assert!(matches!(fault(Variant::Nlhe, "Ah Kh Qh", "", &ANY, 10), Fault::Invalid { .. })); + assert!(matches!(fault(Variant::Nlhe, "Ah", "", &ANY, 10), Fault::Invalid { .. })); + assert!(matches!(fault(Variant::Plo5, "Ah Kh Qh Jh", "", &ANY, 10), Fault::Invalid { .. })); + assert!(matches!(fault(Variant::Nlhe, "", "", &ANY, 10), Fault::Invalid { .. })); +} + +#[test] +fn wrong_exact_villain_card_count_is_invalid() { + let villains = [VillainRange::Exact(cs("2c 3c 4c"))]; + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "", &villains, 10), Fault::Invalid { .. })); +} + +#[test] +fn duplicate_cards_are_inconsistent() { + assert!(matches!(fault(Variant::Nlhe, "Ah Ah", "", &ANY, 10), Fault::Inconsistent(_))); + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "Ah 2c 3d", &ANY, 10), Fault::Inconsistent(_))); + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "2c 2c 3d", &ANY, 10), Fault::Inconsistent(_))); +} + +#[test] +fn exact_villain_clashing_with_dead_cards_is_inconsistent() { + let hero_clash = [VillainRange::Exact(cs("Ah 2c"))]; + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "", &hero_clash, 10), Fault::Inconsistent(_))); + let board_clash = [VillainRange::Exact(cs("2c 3c"))]; + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "2c 7d 8d", &board_clash, 10), Fault::Inconsistent(_))); + let twins = [VillainRange::Exact(cs("2c 3c")), VillainRange::Exact(cs("3c 4c"))]; + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "", &twins, 10), Fault::Inconsistent(_))); +} + +#[test] +fn board_sizes_other_than_0_3_4_5_are_invalid() { + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "2c 3d 4h 5s 6c 7d", &ANY, 10), Fault::Invalid { .. })); + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "2c", &ANY, 10), Fault::Invalid { .. })); + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "2c 3d", &ANY, 10), Fault::Invalid { .. })); +} + +#[test] +fn zero_trials_is_invalid() { + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "", &ANY, 0), Fault::Invalid { .. })); +} + +#[test] +fn deck_exhaustion_is_reported() { + let ten_any: Vec = (0..10).map(|_| VillainRange::Any).collect(); + assert!(matches!(fault(Variant::Plo5, "Ah Kh Qh Jh Th", "", &ten_any, 10), Fault::Exhausted(_))); + let thirty: Vec = (0..30).map(|_| VillainRange::Any).collect(); + assert!(matches!(fault(Variant::Nlhe, "Ah Kh", "", &thirty, 10), Fault::Exhausted(_))); +} + +#[test] +fn exactly_enough_cards_is_fine() { + // 5 hero + 9 * 5 villains = 50, board needs 5 more but only 2 remain: exhausted. + let nine: Vec = (0..9).map(|_| VillainRange::Any).collect(); + assert!(matches!(fault(Variant::Plo5, "Ah Kh Qh Jh Th", "", &nine, 10), Fault::Exhausted(_))); + // 5 hero + 8 * 5 villains = 45, 7 left for a 5-card board. + let eight: Vec = (0..8).map(|_| VillainRange::Any).collect(); + let (hero, board) = (cs("Ah Kh Qh Jh Th"), cs("")); + let query = Query { rules: rules(Variant::Plo5), hero: &hero, board: &board, villains: &eight, trials: 20 }; + assert!(estimate(&query, Rng::seeded(1)).is_ok()); +} diff --git a/tests/equity_properties.rs b/tests/equity_properties.rs new file mode 100644 index 00000000..64172231 --- /dev/null +++ b/tests/equity_properties.rs @@ -0,0 +1,153 @@ +//! Determinism, invariants of the estimate and range filtering. +use std::cell::Cell; + +use pokerfreak::card::{Card, Rank}; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::equity::monte_carlo::estimate; +use pokerfreak::equity::query::Query; +use pokerfreak::equity::villain_range::VillainRange; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{rules, Variant}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +fn run_seeded(variant: Variant, hero: &str, board: &str, villains: &[VillainRange], trials: u32, seed: u64) -> (Estimate, Rng) { + let (hero, board) = (cs(hero), cs(board)); + let query = Query { rules: rules(variant), hero: &hero, board: &board, villains, trials }; + estimate(&query, Rng::seeded(seed)).expect("estimate") +} + +fn nlhe(hero: &str, board: &str, villains: &[VillainRange], trials: u32, seed: u64) -> Estimate { + run_seeded(Variant::Nlhe, hero, board, villains, trials, seed).0 +} + +#[test] +fn same_seed_gives_identical_estimate_and_rng() { + let any = [VillainRange::Any, VillainRange::Any]; + assert_eq!(run_seeded(Variant::Nlhe, "Ah Kd", "", &any, 2_000, 7), run_seeded(Variant::Nlhe, "Ah Kd", "", &any, 2_000, 7)); + let plo = [VillainRange::Any]; + assert_eq!( + run_seeded(Variant::Plo5, "Ah Kd Qc Js 9h", "2c 3d 4h", &plo, 300, 7), + run_seeded(Variant::Plo5, "Ah Kd Qc Js 9h", "2c 3d 4h", &plo, 300, 7) + ); +} + +#[test] +fn different_seeds_usually_differ() { + let any = [VillainRange::Any]; + let a = nlhe("Ah Kd", "", &any, 1_000, 1); + let b = nlhe("Ah Kd", "", &any, 1_000, 2); + assert_ne!(a.share, b.share); +} + +#[test] +fn returned_rng_is_advanced_so_calls_can_be_chained() { + let any = [VillainRange::Any]; + let (first, rng) = run_seeded(Variant::Nlhe, "Ah Kd", "", &any, 500, 3); + assert_ne!(rng, Rng::seeded(3)); + let (hero, board) = (cs("Ah Kd"), cs("")); + let query = Query { rules: rules(Variant::Nlhe), hero: &hero, board: &board, villains: &any, trials: 500 }; + let (second, _) = estimate(&query, rng).unwrap(); + assert_ne!(first.share, second.share); +} + +#[test] +fn estimate_invariants_hold() { + let any = [VillainRange::Any, VillainRange::Any]; + for (hero, board) in [("Ah Kd", ""), ("7c 2d", "Ks Qh Jd"), ("Ts 9s", "8s 7s 2d 3c")] { + let e = nlhe(hero, board, &any, 1_500, 11); + assert_eq!(e.trials, 1_500); + assert!((0.0..=1.0).contains(&e.share)); + assert!(e.win >= 0.0 && e.tie >= 0.0 && e.win + e.tie <= 1.0 + 1e-12); + assert!(e.share >= e.win - 1e-12 && e.share <= e.win + e.tie + 1e-12); + assert!(e.std_error > 0.0 && e.std_error < 0.02); + } +} + +#[test] +fn heads_up_share_is_win_plus_half_the_ties() { + let e = nlhe("Ah Kd", "Ac Kc 7d", &[VillainRange::Any], 3_000, 5); + assert!((e.share - (e.win + e.tie / 2.0)).abs() < 1e-12); +} + +#[test] +fn std_error_matches_binomial_scale_and_shrinks_with_trials() { + let any = [VillainRange::Any]; + let small = nlhe("Ah Kd", "", &any, 1_000, 9); + let large = nlhe("Ah Kd", "", &any, 16_000, 9); + let binomial = (0.65f64 * 0.35 / 1_000.0).sqrt(); + assert!((small.std_error / binomial - 1.0).abs() < 0.25, "{} vs {binomial}", small.std_error); + assert!(large.std_error < small.std_error / 3.0); +} + +#[test] +fn no_villains_means_hero_takes_the_pot() { + let e = nlhe("Ah Kd", "", &[], 50, 1); + assert_eq!((e.win, e.tie, e.share), (1.0, 0.0, 1.0)); +} + +#[test] +fn exact_and_any_ranges_mix() { + let villains = [VillainRange::Exact(cs("Kd Kc")), VillainRange::Any]; + let e = nlhe("Ah As", "", &villains, 8_000, 4); + assert!(e.share > 0.55 && e.share < 0.75, "{}", e.share); +} + +fn is_pair(hand: &[Card]) -> bool { + hand.len() == 2 && hand[0].rank == hand[1].rank +} + +#[test] +fn filter_range_constrains_villain_hands() { + let pairs: &dyn Fn(&[Card]) -> bool = &is_pair; + let vs_pairs = nlhe("Ah Kd", "", &[VillainRange::Filter(pairs)], 20_000, 6); + let vs_any = nlhe("Ah Kd", "", &[VillainRange::Any], 20_000, 6); + // AKo vs random ~ 65 %, vs a pocket pair ~ 45 % (coin-flip-ish race, blockers help slightly). + assert!(vs_any.share > 0.62 && vs_any.share < 0.68, "{}", vs_any.share); + assert!(vs_pairs.share > 0.41 && vs_pairs.share < 0.50, "{}", vs_pairs.share); +} + +#[test] +fn filter_predicate_only_accepted_hands_are_played_and_never_overlap_hero() { + let overlap = Cell::new(false); + let bad_length = Cell::new(false); + let hero = cs("Ah Kd"); + let seen: &dyn Fn(&[Card]) -> bool = &|hand: &[Card]| { + bad_length.set(bad_length.get() || hand.len() != 2); + overlap.set(overlap.get() || hand.iter().any(|c| hero.contains(c))); + hand.iter().all(|c| c.rank >= Rank::Ten) + }; + let e = nlhe("Ah Kd", "", &[VillainRange::Filter(seen)], 2_000, 8); + assert!(!overlap.get() && !bad_length.get()); + assert!(e.share > 0.2 && e.share < 0.7); +} + +#[test] +fn filter_for_strong_hands_lowers_hero_equity() { + let broadway: &dyn Fn(&[Card]) -> bool = &|h: &[Card]| h.iter().all(|c| c.rank >= Rank::Jack); + let strong = nlhe("9h 8h", "", &[VillainRange::Filter(broadway)], 10_000, 2); + let any = nlhe("9h 8h", "", &[VillainRange::Any], 10_000, 2); + assert!(strong.share < any.share - 0.05, "{} vs {}", strong.share, any.share); +} + +#[test] +fn impossible_filter_falls_back_to_an_unfiltered_hand_without_failing() { + let never: &dyn Fn(&[Card]) -> bool = &|_: &[Card]| false; + let rejecting = nlhe("Ah Kd", "", &[VillainRange::Filter(never)], 3_000, 3); + let any = nlhe("Ah Kd", "", &[VillainRange::Any], 3_000, 3); + assert!((rejecting.share - any.share).abs() < 0.05); +} + +#[test] +fn plo5_five_card_hands_are_dealt_to_filters() { + let lengths_ok = Cell::new(true); + let probe: &dyn Fn(&[Card]) -> bool = &|h: &[Card]| { + lengths_ok.set(lengths_ok.get() && h.len() == 5); + true + }; + let (e, _) = run_seeded(Variant::Plo5, "Ah Kd Qc Js 9h", "", &[VillainRange::Filter(probe)], 200, 1); + assert!(lengths_ok.get()); + assert!(e.share > 0.0 && e.share < 1.0); +} diff --git a/tests/equity_reference.rs b/tests/equity_reference.rs new file mode 100644 index 00000000..f1240a09 --- /dev/null +++ b/tests/equity_reference.rs @@ -0,0 +1,158 @@ +//! Monte Carlo equity against published reference values and exact enumeration. +//! +//! Sources: +//! - Preflop matchups: Wikipedia "Texas hold 'em starting hands" (head-to-head table) and +//! PokerStove / ProPokerTools Odds Oracle results: AA vs KK ~ 81.9 / 17.8 (+ ~0.3 tie), +//! AKo vs QQ ~ 43 / 57, AKs vs 22 ~ 50 / 50, AA vs 3 random hands ~ 64.2 %. +//! - Flush draw: "rule of 4 and 2" (9 outs, two cards to come: 1 - 38/47 * 37/46 = 35.0 %). +//! - Exact spots: complete enumeration with `hand::showdown::best` (independent of the sampler). +use pokerfreak::card::{deck, Card}; +use pokerfreak::equity::estimate::Estimate; +use pokerfreak::equity::monte_carlo::estimate; +use pokerfreak::equity::query::Query; +use pokerfreak::equity::villain_range::VillainRange; +use pokerfreak::hand::showdown::best; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{rules, HoleUsage, Variant}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +fn run(variant: Variant, hero: &str, board: &str, villains: &[VillainRange], trials: u32) -> Estimate { + let (hero, board) = (cs(hero), cs(board)); + let query = Query { rules: rules(variant), hero: &hero, board: &board, villains, trials }; + estimate(&query, Rng::seeded(2024)).expect("estimate").0 +} + +fn versus(variant: Variant, hero: &str, villain: &str, board: &str, trials: u32) -> Estimate { + run(variant, hero, board, &[VillainRange::Exact(cs(villain))], trials) +} + +/// Exact hero share against one known hand by enumerating every board completion. +fn exact_share(usage: HoleUsage, hero: &str, villain: &str, board: &str) -> f64 { + let (hero, villain, board) = (cs(hero), cs(villain), cs(board)); + let dead: Vec = hero.iter().chain(&villain).chain(&board).copied().collect(); + let pool = deck::without(&dead); + let missing = 5 - board.len(); + let mut total = 0.0; + let mut count = 0.0; + let mut visit = |extra: &[Card]| { + let full: Vec = board.iter().chain(extra).copied().collect(); + let (h, v) = (best(usage, &hero, &full).unwrap(), best(usage, &villain, &full).unwrap()); + total += if h > v { 1.0 } else if h == v { 0.5 } else { 0.0 }; + count += 1.0; + }; + match missing { + 1 => pool.iter().for_each(|a| visit(&[*a])), + 2 => { + for i in 0..pool.len() { + for j in i + 1..pool.len() { + visit(&[pool[i], pool[j]]); + } + } + } + _ => visit(&[]), + } + total / count +} + +fn close(actual: f64, expected: f64, tolerance: f64) { + assert!((actual - expected).abs() <= tolerance, "expected {expected} +- {tolerance}, got {actual}"); +} + +#[test] +fn aces_versus_kings_preflop_is_about_82_percent() { + let e = versus(Variant::Nlhe, "Ah As", "Kd Kc", "", 30_000); + close(e.share, 0.82, 0.015); +} + +#[test] +fn ace_king_offsuit_versus_queens_is_about_43_percent() { + let e = versus(Variant::Nlhe, "Ah Kd", "Qc Qs", "", 30_000); + close(e.share, 0.43, 0.015); +} + +#[test] +fn ace_king_suited_versus_deuces_is_a_coin_flip() { + let e = versus(Variant::Nlhe, "Ah Kh", "2c 2d", "", 30_000); + close(e.share, 0.50, 0.02); +} + +#[test] +fn river_royal_flush_wins_every_trial() { + let e = versus(Variant::Nlhe, "Ah Kh", "2c 3d", "Qh Jh Th 7c 8d", 500); + assert_eq!((e.win, e.tie, e.share), (1.0, 0.0, 1.0)); +} + +#[test] +fn river_dominated_hand_loses_every_trial() { + let e = versus(Variant::Nlhe, "2c 3d", "Ah Kh", "Qh Jh Th 7c 8d", 500); + assert_eq!((e.win, e.tie, e.share), (0.0, 0.0, 0.0)); +} + +#[test] +fn river_board_plays_splits_the_pot_exactly() { + let e = versus(Variant::Nlhe, "2c 3c", "4d 5d", "Ah Kd Qc Jh Ts", 500); + assert_eq!((e.win, e.tie, e.share), (0.0, 1.0, 0.5)); +} + +#[test] +fn river_three_way_tie_gives_a_third() { + let villains = [VillainRange::Exact(cs("4d 5d")), VillainRange::Exact(cs("6d 7d"))]; + let e = run(Variant::Nlhe, "2c 3c", "Ah Kd Qc Jh Ts", &villains, 200); + close(e.share, 1.0 / 3.0, 1e-12); +} + +#[test] +fn flop_nut_flush_draw_versus_overpair_matches_the_nine_out_rule() { + let spot = ("Kh 4h", "Ac Ad", "Qs 2h 9h"); + let e = versus(Variant::Nlhe, spot.0, spot.1, spot.2, 30_000); + close(e.share, 0.35, 0.03); + close(e.share, exact_share(HoleUsage::BestFiveOfAll, spot.0, spot.1, spot.2), 0.015); +} + +#[test] +fn aces_against_three_random_hands_is_about_64_percent() { + let villains = [VillainRange::Any, VillainRange::Any, VillainRange::Any]; + let e = run(Variant::Nlhe, "Ah As", "", &villains, 30_000); + close(e.share, 0.642, 0.02); +} + +#[test] +fn ace_king_offsuit_against_one_random_hand_is_about_65_percent() { + // PokerStove: AKo vs random hand = 65.3 %. + let e = run(Variant::Nlhe, "Ah Kd", "", &[VillainRange::Any], 30_000); + close(e.share, 0.653, 0.015); +} + +#[test] +fn plo5_river_nut_flush_versus_lower_flush_is_certain() { + // Both flush; hero holds Ah 4h, villain 8h 7h: ace-high flush wins. + let e = versus(Variant::Plo5, "Ah 4h Kc Qc Jd", "8h 7h Ac Qd Jc", "2h 5h 9h Kd 3c", 300); + assert_eq!((e.win, e.share), (1.0, 1.0)); +} + +#[test] +fn plo5_river_board_flush_does_not_play_without_two_suited_hole_cards() { + // Board is five hearts. Hero holds one heart, villain two hearts: villain makes the flush. + let e = versus(Variant::Plo5, "Ah Ks Kd Qc 2c", "9h 8h 4s 3d 3c", "Kh Qh Jh 7h 5h", 300); + assert_eq!(e.share, 0.0); +} + +#[test] +fn plo5_turn_spot_matches_exact_enumeration() { + let (hero, villain, board) = ("As Ah Kd Kc Qs", "9h 9c 5d 4s 2h", "Jc 7d 3h 2s"); + let exact = exact_share(HoleUsage::ExactlyTwoHole, hero, villain, board); + let e = versus(Variant::Plo5, hero, villain, board, 20_000); + close(e.share, exact, 0.015); +} + +#[test] +fn plo5_flop_versus_random_hands_is_dominated_by_the_nut_draw() { + // Sanity bound (no published table for PLO5 flops): AAKKQ with a nut-flush draw plus top + // overpair-ish holdings is a clear favourite over one random five-card hand. + let villains = [VillainRange::Any]; + let e = run(Variant::Plo5, "As Ks Ah Kh Qd", "Qs 7s 2c", &villains, 6_000); + assert!(e.share > 0.6 && e.share < 0.95, "got {}", e.share); +} diff --git a/tests/hand_five_cards.rs b/tests/hand_five_cards.rs new file mode 100644 index 00000000..98c8412e --- /dev/null +++ b/tests/hand_five_cards.rs @@ -0,0 +1,117 @@ +//! Five-card evaluation: categories, kickers, wheel, ordering. +//! Category ranking order: standard poker hand ranking (Wikipedia "List of poker hands"). +use pokerfreak::card::Card; +use pokerfreak::hand::category::Category; +use pokerfreak::hand::five::evaluate; +use pokerfreak::hand::strength::Strength; + +fn s(text: &str) -> Strength { + let cards = Card::parse_list(text).expect("cards"); + let five: [Card; 5] = cards.try_into().expect("five cards"); + evaluate(&five) +} + +#[test] +fn recognises_every_category() { + assert_eq!(s("Ah Kd 9c 5s 3d").category, Category::HighCard); + assert_eq!(s("Ah Ad 9c 5s 3d").category, Category::Pair); + assert_eq!(s("Ah Ad 9c 9s 3d").category, Category::TwoPair); + assert_eq!(s("Ah Ad Ac 9s 3d").category, Category::ThreeOfAKind); + assert_eq!(s("5h 6d 7c 8s 9d").category, Category::Straight); + assert_eq!(s("Ah 9h 7h 5h 3h").category, Category::Flush); + assert_eq!(s("Ah Ad Ac 9s 9d").category, Category::FullHouse); + assert_eq!(s("Ah Ad Ac As 3d").category, Category::FourOfAKind); + assert_eq!(s("5h 6h 7h 8h 9h").category, Category::StraightFlush); +} + +#[test] +fn categories_are_totally_ordered_in_poker_order() { + let ladder = [ + s("Ah Kd 9c 5s 3d"), + s("2h 2d 9c 5s 3d"), + s("2h 2d 3c 3s 4d"), + s("2h 2d 2c 5s 3d"), + s("2h 3d 4c 5s 6d"), + s("2h 4h 7h 9h Jh"), + s("2h 2d 2c 5s 5d"), + s("2h 2d 2c 2s 3d"), + s("2h 3h 4h 5h 6h"), + ]; + assert!(ladder.windows(2).all(|w| w[0] < w[1])); +} + +#[test] +fn wheel_is_the_lowest_straight_and_ace_plays_low() { + let wheel = s("Ah 2d 3c 4s 5d"); + assert_eq!(wheel.category, Category::Straight); + assert!(wheel < s("2h 3d 4c 5s 6d")); + assert!(wheel > s("Ah Ad Ac Ks Qd")); +} + +#[test] +fn broadway_is_the_highest_straight_and_no_wraparound() { + assert!(s("Th Jd Qc Ks Ad") > s("9h Td Jc Qs Kd")); + assert_eq!(s("Qh Kd Ac 2s 3d").category, Category::HighCard); + assert_eq!(s("Kh Ad 2c 3s 4d").category, Category::HighCard); +} + +#[test] +fn steel_wheel_is_a_straight_flush_below_a_six_high_one() { + let steel = s("Ah 2h 3h 4h 5h"); + assert_eq!(steel.category, Category::StraightFlush); + assert!(steel < s("2h 3h 4h 5h 6h")); + assert!(s("Th Jh Qh Kh Ah") > s("9h Th Jh Qh Kh")); +} + +#[test] +fn kickers_decide_within_a_category() { + assert!(s("Ah Ad Kc 5s 3d") > s("Ah Ad Qc Js Td")); + assert!(s("Ah Ad Kc 5s 3d") > s("Ah Ad Kc 4s 3d")); + assert!(s("Ah Ad Kc Qs Jd") > s("Kh Kd Ac Qs Jd")); + assert!(s("Ah Kd Qc Js 9d") > s("Ah Kd Qc Js 8d")); +} + +#[test] +fn two_pair_compares_high_pair_then_low_pair_then_kicker() { + assert!(s("Ah Ad 3c 3s 2d") > s("Kh Kd Qc Qs Jd")); + assert!(s("Kh Kd Qc Qs 2d") > s("Kh Kd Jc Js Ad")); + assert!(s("Kh Kd Qc Qs Ad") > s("Kh Kd Qc Qs 2d")); +} + +#[test] +fn full_house_compares_trips_before_pair() { + assert!(s("3h 3d 3c 2s 2d") > s("2h 2d 2c As Ad")); + assert!(s("3h 3d 3c As Ad") > s("3h 3d 3c Ks Kd")); +} + +#[test] +fn quads_compare_rank_then_kicker() { + assert!(s("3h 3d 3c 3s 2d") > s("2h 2d 2c 2s Ad")); + assert!(s("3h 3d 3c 3s Ad") > s("3h 3d 3c 3s Kd")); +} + +#[test] +fn flush_compares_card_by_card() { + assert!(s("Ah Kh 9h 5h 3h") > s("Ah Kh 9h 5h 2h")); + assert!(s("Ah Kh 9h 5h 3h") > s("Qh Jh Th 9h 7h")); +} + +#[test] +fn order_of_cards_and_suits_do_not_matter() { + assert_eq!(s("Ah Ad 9c 9s 3d"), s("3c 9d Ad 9h As")); + assert_eq!(s("Ah Kd 9c 5s 3d"), s("3h 5d 9s Kc Ac")); + assert_eq!(s("5h 6d 7c 8s 9d"), s("9c 8d 7s 6h 5c")); +} + +#[test] +fn identical_ranks_in_different_suits_tie() { + assert_eq!(s("Ah Kd 9c 5s 3d"), s("Ac Kh 9s 5d 3c")); +} + +#[test] +fn weakest_and_strongest_hands_bound_everything() { + let worst = s("7h 5d 4c 3s 2d"); + let best = s("Th Jh Qh Kh Ah"); + assert!(worst < best); + assert_eq!(worst.category, Category::HighCard); +} diff --git a/tests/hand_showdown.rs b/tests/hand_showdown.rs new file mode 100644 index 00000000..36864602 --- /dev/null +++ b/tests/hand_showdown.rs @@ -0,0 +1,116 @@ +//! Best-hand selection per variant family and its failure modes. +//! Omaha rule (exactly 2 hole + exactly 3 board): standard Omaha rules, Wikipedia "Omaha hold 'em". +use pokerfreak::card::Card; +use pokerfreak::fault::Fault; +use pokerfreak::hand::category::Category; +use pokerfreak::hand::showdown::best; +use pokerfreak::hand::strength::Strength; +use pokerfreak::variant::HoleUsage; +use pokerfreak::variant::HoleUsage::{BestFiveOfAll as Holdem, ExactlyTwoHole as Omaha}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +fn run(usage: HoleUsage, hole: &str, board: &str) -> Strength { + best(usage, &cs(hole), &cs(board)).expect("strength") +} + +#[test] +fn holdem_picks_best_five_of_seven() { + assert_eq!(run(Holdem, "Ah Kh", "Qh Jh Th 2c 3d").category, Category::StraightFlush); +} + +#[test] +fn holdem_board_plays() { + let a = run(Holdem, "2c 3d", "Ah Kh Qh Jh Th"); + let b = run(Holdem, "4c 5d", "Ah Kh Qh Jh Th"); + assert_eq!(a, b); + assert_eq!(a.category, Category::StraightFlush); +} + +#[test] +fn holdem_works_with_five_and_six_cards() { + assert_eq!(run(Holdem, "Ah Ad", "Ac Ks 2d").category, Category::ThreeOfAKind); + assert_eq!(run(Holdem, "Ah Ad", "Ac Ks 2d 9h").category, Category::ThreeOfAKind); +} + +#[test] +fn holdem_kicker_split_and_win() { + let board = "Ah Kd 7c 4s 2d"; + assert_eq!(run(Holdem, "Ac Qd", board), run(Holdem, "As Qh", board)); + assert!(run(Holdem, "Ac Jd", board) < run(Holdem, "As Qh", board)); +} + +#[test] +fn holdem_seven_card_flush_beats_straight() { + assert_eq!(run(Holdem, "9h 8h", "7h 6h Ad Tc 2h").category, Category::Flush); +} + +#[test] +fn holdem_two_trips_make_a_full_house() { + let s = run(Holdem, "Ah Ad", "Ac Kd Ks Kh 2c"); + assert_eq!(s.category, Category::FullHouse); + // Aces full of kings outranks kings full of queens. + assert!(s > run(Holdem, "Qh Qd", "Qc Kd Ks Kh 2c")); +} + +#[test] +fn omaha_needs_two_hole_cards_for_a_flush() { + let board = "Kh Qh 9h 4h 2c"; + assert_ne!(run(Omaha, "Ah 7c 7d 3s 3c", board).category, Category::Flush); + assert_eq!(run(Holdem, "Ah 7c", board).category, Category::Flush); + assert_eq!(run(Omaha, "Ah 7h 3s 3c 8d", board).category, Category::Flush); +} + +#[test] +fn omaha_board_straight_does_not_play_without_two_hole_cards() { + let board = "5h 6d 7c 8s 9d"; + assert_eq!(run(Holdem, "Ac Ad", board).category, Category::Straight); + assert_eq!(run(Omaha, "Ac Ad 2c 2d Kh", board).category, Category::Pair); +} + +#[test] +fn omaha_exactly_two_blocks_quads_from_three_hole_cards() { + let s = run(Omaha, "Ac Ad Ah 2c 3d", "As Kd 7c 8h 9d"); + assert_eq!(s.category, Category::ThreeOfAKind); +} + +#[test] +fn omaha_picks_the_best_of_all_pairings() { + // 9h 8h + 7h 6h 5c is a straight flush only with 5h; here 9h 8h + 7h 6h 2h is a flush. + let s = run(Omaha, "9h 8h Ac Kd 2s", "7h 6h 5c Tc 2h"); + assert_eq!(s.category, Category::Flush); +} + +#[test] +fn omaha_five_hole_cards_nut_flush_beats_lower_flush() { + let board = "2h 5h 9h Kd 3c"; + let nut = run(Omaha, "Ah 4h Kc Qc Jd", board); + let low = run(Omaha, "8h 7h Ac Qc Jd", board); + assert_eq!(nut.category, Category::Flush); + assert!(nut > low); +} + +#[test] +fn omaha_split_pot_on_identical_best_five() { + let board = "Ah Kd Qc Jh Ts"; + assert_eq!(run(Omaha, "2c 3c 4d 5d 6d", board), run(Omaha, "2d 3d 4c 5c 6c", board)); +} + +#[test] +fn omaha_needs_three_board_cards() { + assert!(best(Omaha, &cs("Ac Ad Kc Kd Qh"), &cs("2c 3d 4h")).is_ok()); + assert!(best(Omaha, &cs("Ac Ad Kc Kd Qh"), &cs("2c 3d")).is_err()); +} + +#[test] +fn bad_input_is_a_fault_never_a_panic() { + assert!(matches!(best(Holdem, &cs("Ah Kh"), &cs("Qh Jh")), Err(Fault::Invalid { .. }))); + assert!(matches!(best(Holdem, &cs("Ah Kh"), &cs("Qh Jh Th 2c 3d 4s")), Err(Fault::Invalid { .. }))); + assert!(best(Holdem, &[], &[]).is_err()); + assert!(best(Holdem, &cs("Ah Ah"), &cs("Qh Jh Th")).is_err()); + assert!(best(Holdem, &cs("Ah Kh"), &cs("Ah Jh Th")).is_err()); + assert!(best(Omaha, &cs("Ac"), &cs("2c 3d 4h")).is_err()); + assert!(best(Omaha, &cs("Ac Ac Kc Kd Qh"), &cs("2c 3d 4h")).is_err()); +}