diff --git a/src/card/deck.rs b/src/card/deck.rs index 14c4a6f3..4b37a5fe 100644 --- a/src/card/deck.rs +++ b/src/card/deck.rs @@ -2,13 +2,26 @@ use super::Card; use crate::rng::Rng; +use crate::variant::DeckRule; +/// The 52-card deck, rank-major. pub fn full() -> Vec { - (0..52).filter_map(Card::from_index).collect() + of(DeckRule::FULL) } pub fn without(dead: &[Card]) -> Vec { - full().into_iter().filter(|c| !dead.contains(c)).collect() + without_in(DeckRule::FULL, dead) +} + +/// Every card the rule allows (all four suits from `rule.lowest` up to the ace), rank-major. +/// `DeckRule::FULL` gives exactly the order of `full`; `DeckRule::SHORT` has 36 cards. +pub fn of(rule: DeckRule) -> Vec { + (0..52).filter_map(Card::from_index).filter(|c| rule.contains(c.rank)).collect() +} + +/// The rule's deck minus `dead`. Dead cards that are not in the deck are ignored. +pub fn without_in(rule: DeckRule, dead: &[Card]) -> Vec { + of(rule).into_iter().filter(|c| !dead.contains(c)).collect() } /// Draws `count` distinct cards from `pool` (partial Fisher–Yates on a private copy). diff --git a/src/equity/deck_capacity.rs b/src/equity/deck_capacity.rs new file mode 100644 index 00000000..f5a1642e --- /dev/null +++ b/src/equity/deck_capacity.rs @@ -0,0 +1,27 @@ +//! How many cards a table needs from the rule's deck. +//! +//! Burned cards are unseen random cards: they take room in the deck but never change equity, +//! so the simulation does not deal them, it only checks that they would fit. + +use crate::variant::{DeckRule, Rules}; + +/// Cards a restricted deck must keep back for the burns. +/// A full 52-card deck reserves none: full-deck tables with many hands (9-handed Omaha with +/// five hole cards) are dealt without burning in practice, and 52 cards leave no room for them. +pub fn burn_reserve(rules: &Rules) -> usize { + if rules.deck == DeckRule::FULL { + 0 + } else { + rules.burns + } +} + +/// Cards needed for `hands` complete hands, a five-card board and the burn reserve. +pub fn cards_needed(rules: &Rules, hands: usize) -> usize { + hands * rules.hole_cards + 5 + burn_reserve(rules) +} + +/// True when that many hands fit into the rule's deck. +pub fn fits(rules: &Rules, hands: usize) -> bool { + cards_needed(rules, hands) <= rules.deck.size() +} diff --git a/src/equity/mod.rs b/src/equity/mod.rs index 59502954..6548c993 100644 --- a/src/equity/mod.rs +++ b/src/equity/mod.rs @@ -1,5 +1,6 @@ //! Equity of hero against estimated villain ranges, Monte Carlo with an explicit seed. +pub mod deck_capacity; pub mod estimate; pub mod monte_carlo; pub mod outcome; diff --git a/src/equity/monte_carlo.rs b/src/equity/monte_carlo.rs index ea0023fe..4bb92a6b 100644 --- a/src/equity/monte_carlo.rs +++ b/src/equity/monte_carlo.rs @@ -7,7 +7,7 @@ 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::hand::showdown::judge; use crate::rng::Rng; /// Seeded Monte Carlo equity. Same query + same rng ⇒ same estimate. @@ -25,7 +25,7 @@ pub fn estimate(query: &Query, rng: Rng) -> Result<(Estimate, Rng), Fault> { /// 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 rules = &query.rules; let accept_all = |_: &[Card]| true; let mut front = 0; let mut rng = rng; @@ -51,7 +51,7 @@ fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rn 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 hero = judge(rules, query.hero, &board)?; let mut rivals_best = None; let mut rivals_tied = 0u32; for (villain, start) in query.villains.iter().zip(&starts) { @@ -60,7 +60,7 @@ fn play_trial(query: &Query, pool: &mut [Card], rng: Rng) -> Result<(Outcome, Rn (_, Some(s)) => &pool[*s..*s + k], (_, None) => &[], }; - let strength = best(usage, hand, &board)?; + let strength = judge(rules, hand, &board)?; match rivals_best { Some(top) if strength < top => {} Some(top) if strength == top => rivals_tied += 1, diff --git a/src/equity/validate.rs b/src/equity/validate.rs index 789e833c..00da89ce 100644 --- a/src/equity/validate.rs +++ b/src/equity/validate.rs @@ -1,5 +1,6 @@ //! Query checks. Everything that can make a simulation meaningless is a `Fault` here. +use super::deck_capacity::burn_reserve; use super::query::Query; use super::villain_range::VillainRange; use crate::card::{deck, Card}; @@ -26,9 +27,12 @@ pub fn remaining_deck(query: &Query) -> Result, Fault> { 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); + if let Some(card) = dead.iter().find(|c| !query.rules.deck.contains(c.rank)) { + return Err(invalid("cards", format!("{} is not in the deck", card.short()))); + } + let pool = deck::without_in(query.rules.deck, &dead); let random = query.villains.iter().filter(|v| !matches!(v, VillainRange::Exact(_))).count(); - let needed = random * k + (5 - query.board.len()); + let needed = random * k + (5 - query.board.len()) + burn_reserve(&query.rules); if needed > pool.len() { return Err(Fault::Exhausted(format!("{needed} cards needed, {} left in the deck", pool.len()))); } diff --git a/src/guard/validate.rs b/src/guard/validate.rs index 5604152a..0bbb097d 100644 --- a/src/guard/validate.rs +++ b/src/guard/validate.rs @@ -1,3 +1,5 @@ +use crate::card::Card; +use crate::equity::deck_capacity::fits; use crate::fault::Fault; use crate::game::{ActionKind, Spot}; @@ -43,6 +45,32 @@ fn cards(spot: &Spot) -> Result<(), Fault> { Ok(()) } +fn outside_deck(spot: &Spot) -> Result<(), Fault> { + let deck = spot.rules().deck; + let strange = |field: &str, cards: &[Card]| match cards.iter().find(|c| !deck.contains(c.rank)) { + Some(card) => Err(invalid( + field, + &format!("{} is not in the {} deck", card.short(), spot.variant.name()), + )), + None => Ok(()), + }; + strange("heroCards", &spot.hero_cards)?; + strange("board", &spot.board) +} + +/// Hero plus every live villain must be dealt a hand from the deck, with the board and burns. +fn players_fit(spot: &Spot) -> Result<(), Fault> { + let players = 1 + spot.live_villains().count(); + if fits(&spot.rules(), players) { + Ok(()) + } else { + Err(invalid( + "villains", + &format!("{players} players do not fit the {} deck with board and burns", spot.variant.name()), + )) + } +} + fn chips(spot: &Spot) -> Result<(), Fault> { if !(spot.big_blind.is_finite() && spot.big_blind > 0.0) { return Err(invalid("bigBlind", "must be a finite, positive amount")); @@ -93,6 +121,8 @@ fn actions(spot: &Spot) -> Result<(), Fault> { /// Consistency check of a decoded spot (cards, counts, chips, sizes, legal actions). pub fn check(spot: Spot) -> Result { cards(&spot)?; + outside_deck(&spot)?; + players_fit(&spot)?; chips(&spot)?; actions(&spot)?; Ok(spot) diff --git a/src/hand/five.rs b/src/hand/five.rs index 8997bee0..1d5c2096 100644 --- a/src/hand/five.rs +++ b/src/hand/five.rs @@ -3,12 +3,19 @@ use super::category::Category; use super::strength::Strength; use crate::card::Card; +use crate::variant::{DeckRule, HandRanking}; +/// Standard rules, full deck (ace low in A-2-3-4-5 only). pub fn evaluate(cards: &[Card; 5]) -> Strength { + evaluate_in(DeckRule::FULL, HandRanking::Standard, cards) +} + +/// Five cards under a deck rule (where the ace plays low) and a category ranking. +pub fn evaluate_in(deck: DeckRule, ranking: HandRanking, 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 straight_high = straight_high(deck, &groups); let ranks = tie_break(&groups); let category = match (straight_high, flush, groups[0].0, groups[1].0) { (Some(_), true, _, _) => Category::StraightFlush, @@ -25,7 +32,7 @@ pub fn evaluate(cards: &[Card; 5]) -> Strength { (Category::Straight | Category::StraightFlush, Some(high)) => [high, 0, 0, 0, 0], _ => ranks, }; - Strength { category, ranks } + Strength::new(ranking, category, ranks) } fn rank_counts(cards: &[Card; 5]) -> [u8; 15] { @@ -55,13 +62,16 @@ fn tie_break(groups: &[(u8, u8); 5]) -> [u8; 5] { 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 { +/// High card of the straight when the five cards are five consecutive ranks. +/// The ace also plays below the deck's lowest rank: A-2-3-4-5 (five high) in the full deck, +/// A-6-7-8-9 (nine high) in the short deck. +fn straight_high(deck: DeckRule, 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 + let low = deck.lowest.value(); match (distinct, ranks) { (false, _) => None, - (true, [14, 5, 4, 3, 2]) => Some(5), + (true, [14, a, b, c, d]) if [a, b, c, d] == [low + 3, low + 2, low + 1, low] => Some(low + 3), (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 19f7ece8..fb8a3a88 100644 --- a/src/hand/mod.rs +++ b/src/hand/mod.rs @@ -2,6 +2,7 @@ pub mod category; pub mod five; +pub mod ranking_order; pub mod showdown; pub mod strength; pub mod subset; diff --git a/src/hand/ranking_order.rs b/src/hand/ranking_order.rs new file mode 100644 index 00000000..cd197a04 --- /dev/null +++ b/src/hand/ranking_order.rs @@ -0,0 +1,18 @@ +//! Where each category sits in the ladder of a given hand ranking (higher = stronger). + +use super::category::Category; +use crate::variant::HandRanking; + +/// Indexed by `Category as usize`: high card … straight flush. +const STANDARD: [u8; 9] = [0, 1, 2, 3, 4, 5, 6, 7, 8]; +/// Flush and full house swap places; the straight stays above three of a kind +/// (some short deck rule sets put trips above the straight, this crate does not). +const FLUSH_OVER_FULL_HOUSE: [u8; 9] = [0, 1, 2, 3, 4, 6, 5, 7, 8]; + +pub fn place(ranking: HandRanking, category: Category) -> u8 { + let ladder = match ranking { + HandRanking::Standard => &STANDARD, + HandRanking::FlushOverFullHouse => &FLUSH_OVER_FULL_HOUSE, + }; + ladder[category as usize] +} diff --git a/src/hand/showdown.rs b/src/hand/showdown.rs index 5b004c99..d9078012 100644 --- a/src/hand/showdown.rs +++ b/src/hand/showdown.rs @@ -1,19 +1,18 @@ //! Best hand for a player under the variant's hole-card usage rule. -use super::five::evaluate; +use super::five::{evaluate, evaluate_in}; use super::strength::Strength; use super::subset::{masks, pick}; use crate::card::Card; use crate::fault::Fault; use crate::variant::{HoleUsage, Rules}; +/// Standard rules on the full deck: ace low in A-2-3-4-5, full house beats flush. /// Hold'em family: 5-7 cards in total. Omaha family: >= 2 hole and 3-5 board cards. +/// Variants with their own deck or ladder go through `judge`. 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), - } + select(usage, &evaluate, hole, board) } fn invalid(detail: &str) -> Fault { @@ -30,19 +29,31 @@ fn distinct(hole: &[Card], board: &[Card]) -> Result<(), Fault> { } } -fn best_of_all(hole: &[Card], board: &[Card]) -> Result { +fn select( + usage: HoleUsage, + eval: &dyn Fn(&[Card; 5]) -> Strength, + hole: &[Card], + board: &[Card], +) -> Result { + match usage { + HoleUsage::BestFiveOfAll => best_of_all(eval, hole, board), + HoleUsage::ExactlyTwoHole => exactly_two(eval, hole, board), + } +} + +fn best_of_all(eval: &dyn Fn(&[Card; 5]) -> Strength, 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)) + .map(|five| eval(&five)) .max() .ok_or_else(|| invalid("no five-card selection")) } -fn exactly_two(hole: &[Card], board: &[Card]) -> Result { +fn exactly_two(eval: &dyn Fn(&[Card; 5]) -> Strength, 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")); } @@ -50,13 +61,26 @@ fn exactly_two(hole: &[Card], board: &[Card]) -> Result { 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)) + .map(|five| eval(&five)) .max() .ok_or_else(|| invalid("no five-card selection")) } -/// Best hand under the full variant rules (hole usage, deck, category order). -/// Every caller outside `hand` should use this. +fn outside_deck(rules: &Rules, hole: &[Card], board: &[Card]) -> Option { + hole.iter().chain(board).find(|c| !rules.deck.contains(c.rank)).copied() +} + +/// Best hand under the full variant rules: hole usage, the deck (which ranks exist, where the ace +/// plays low) and the category ladder (`rules.ranking`). Every caller outside `hand` should use this. +/// +/// Cards that are not in the rule's deck are `Fault::Invalid` (a 5 in short deck). +/// Straights rank above three of a kind under every ladder here; some short deck rule sets swap +/// those two, this crate does not. pub fn judge(rules: &Rules, hole: &[Card], board: &[Card]) -> Result { - best(rules.hole_usage, hole, board) + distinct(hole, board)?; + if let Some(card) = outside_deck(rules, hole, board) { + return Err(invalid(&format!("{} is not in the deck", card.short()))); + } + let eval = |five: &[Card; 5]| evaluate_in(rules.deck, rules.ranking, five); + select(rules.hole_usage, &eval, hole, board) } diff --git a/src/hand/strength.rs b/src/hand/strength.rs index 2500939b..c7f6e964 100644 --- a/src/hand/strength.rs +++ b/src/hand/strength.rs @@ -1,10 +1,20 @@ use super::category::Category; +use super::ranking_order::place; +use crate::variant::HandRanking; -/// 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. +/// Totally ordered hand value: the category's place in the variant's ladder first +/// (`order`), then the tie-break ranks (pip values, most significant first; unused slots are 0). +/// Equal strengths are split pots. Strengths of different rankings must not be compared. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Strength { + /// Place of `category` under the ranking this value was made with (derived order starts here). + pub order: u8, pub category: Category, pub ranks: [u8; 5], } + +impl Strength { + pub fn new(ranking: HandRanking, category: Category, ranks: [u8; 5]) -> Strength { + Strength { order: place(ranking, category), category, ranks } + } +} diff --git a/src/preflop/hand_percentile.rs b/src/preflop/hand_percentile.rs index 4ac1dfe0..6e1a0316 100644 --- a/src/preflop/hand_percentile.rs +++ b/src/preflop/hand_percentile.rs @@ -1,15 +1,19 @@ use super::holdem_percentile::holdem_percentile; use super::plo5_percentile::plo5_percentile; +use super::short_deck_percentile::short_deck_percentile; use crate::card::Card; -use crate::variant::{rules, Variant}; +use crate::variant::{rules, DeckRule, Variant}; /// Strength percentile of a starting hand: 0.0 = best possible, 1.0 = worst. -/// Hold'em-family hands use a 169-class ranking table; PLO5 uses a structural score. +/// Two-card hands use a class ranking table chosen by the variant's deck (169 classes for the +/// full deck, 81 for the short deck); PLO5 uses a structural score. /// Anything that is not a valid hand for the variant is `1.0`. pub fn percentile(variant: Variant, hole: &[Card]) -> f64 { - match rules(variant).hole_cards { - 2 => holdem_percentile(hole), - 5 => plo5_percentile(hole), + let rules = rules(variant); + match (rules.hole_cards, rules.deck) { + (2, deck) if deck == DeckRule::SHORT => short_deck_percentile(hole), + (2, _) => holdem_percentile(hole), + (5, _) => plo5_percentile(hole), _ => 1.0, } } diff --git a/src/preflop/mod.rs b/src/preflop/mod.rs index 55cd7954..72617644 100644 --- a/src/preflop/mod.rs +++ b/src/preflop/mod.rs @@ -22,3 +22,5 @@ pub mod push_chart; pub mod reason; pub mod situation; pub mod width_factor; +pub mod short_deck_percentile; +pub mod short_deck_ranking; diff --git a/src/preflop/short_deck_percentile.rs b/src/preflop/short_deck_percentile.rs new file mode 100644 index 00000000..af1c81cc --- /dev/null +++ b/src/preflop/short_deck_percentile.rs @@ -0,0 +1,68 @@ +//! Percentile of a two-card short deck hand from the 81-class ranking. + +use super::short_deck_ranking::RANKING; +use crate::card::{Card, Rank}; + +/// 9 ranks: 9 pairs x 6 + 36 suited x 4 + 36 offsuit x 12. +const TOTAL_COMBOS: u32 = 630; + +/// Index of the lowest rank in the deck (Six) among all 13 ranks. +const LOWEST: usize = Rank::Six as usize; + +/// `[row][col]` with the same layout as the hold'em table: pairs on the diagonal, suited above +/// it (`[high][low]`), offsuit below it (`[low][high]`). Each cell holds the share of combos +/// that rank strictly better plus half of the class's own combos, so the mean is 0.5. +static TABLE: [[f64; 9]; 9] = build_table(); + +const fn rank_index(symbol: u8) -> usize { + match symbol { + b'6' => 0, + b'7' => 1, + b'8' => 2, + b'9' => 3, + b'T' => 4, + b'J' => 5, + b'Q' => 6, + b'K' => 7, + _ => 8, + } +} + +const fn build_table() -> [[f64; 9]; 9] { + let mut table = [[1.0; 9]; 9]; + let mut before = 0u32; + let mut i = 0; + while i < RANKING.len() { + let class = RANKING[i].as_bytes(); + let (high, low) = (rank_index(class[0]), rank_index(class[1])); + let (weight, row, col) = if high == low { + (6, high, high) + } else if class[2] == b's' { + (4, high, low) + } else { + (12, low, high) + }; + table[row][col] = (before as f64 + weight as f64 / 2.0) / TOTAL_COMBOS as f64; + before += weight; + i += 1; + } + table +} + +/// `1.0` unless `hole` is exactly two distinct cards of the short deck (six or higher). +pub fn short_deck_percentile(hole: &[Card]) -> f64 { + match hole { + [a, b] if a != b && a.rank >= Rank::Six && b.rank >= Rank::Six => { + let (high, low) = if a.rank >= b.rank { (a, b) } else { (b, a) }; + let (h, l) = (high.rank as usize - LOWEST, low.rank as usize - LOWEST); + if h == l { + TABLE[h][h] + } else if high.suit == low.suit { + TABLE[h][l] + } else { + TABLE[l][h] + } + } + _ => 1.0, + } +} diff --git a/src/preflop/short_deck_ranking.rs b/src/preflop/short_deck_ranking.rs new file mode 100644 index 00000000..5e5754a7 --- /dev/null +++ b/src/preflop/short_deck_ranking.rs @@ -0,0 +1,19 @@ +//! The 81 two-card starting-hand classes of the short deck (6+ hold'em), best first. +//! +//! Source: all-in equity of each class against one uniformly random hand of the 36-card deck +//! (five-card board run out; flush beats full house, ace plays low in A-6-7-8-9), measured by +//! seeded Monte Carlo with 10 000 000 deals per class (standard error about 0.0002): AA 73.1 % +//! down to 76o 35.3 %. Reproduce with +//! `cargo test --release --test short_deck_ranking_generate -- --ignored --nocapture` +//! (seed of class i = 1000 + i, see that test). Neighbours closer than the error may swap. +//! Notation as in `holdem_ranking`: `AKs` suited, `AKo` offsuit, `AA` pair, higher rank first. + +pub const RANKING: [&str; 81] = [ + "AA", "KK", "QQ", "JJ", "TT", "AKs", "AQs", "AKo", "AJs", "KQs", "AQo", "ATs", "KJs", "AJo", + "QJs", "KTs", "KQo", "JTs", "QTs", "99", "KJo", "ATo", "A9s", "QJo", "KTo", "JTo", "QTo", + "A8s", "A9o", "K9s", "T9s", "A8o", "Q9s", "J9s", "A7s", "K9o", "T9o", "Q9o", "J9o", "A7o", + "88", "A6s", "K8s", "98s", "T8s", "Q8s", "J8s", "K7s", "A6o", "K8o", "98o", "T8o", "Q8o", + "J8o", "K7o", "K6s", "97s", "T7s", "Q7s", "J7s", "77", "Q6s", "K6o", "97o", "87s", "T7o", + "Q7o", "J7o", "96s", "Q6o", "T6s", "J6s", "87o", "96o", "86s", "T6o", "J6o", "66", "76s", + "86o", "76o", +]; diff --git a/tests/short_deck_deck.rs b/tests/short_deck_deck.rs new file mode 100644 index 00000000..58be81dc --- /dev/null +++ b/tests/short_deck_deck.rs @@ -0,0 +1,75 @@ +//! Deck construction per deck rule. +//! Reference: short deck (6+ hold'em) removes the twos through fives: 9 ranks x 4 suits = 36 cards +//! (Wikipedia, "Six-plus hold'em"). + +use pokerfreak::card::{deck, Card, Rank, Suit}; +use pokerfreak::rng::Rng; +use pokerfreak::variant::DeckRule; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +#[test] +fn short_deck_has_36_cards_and_no_twos_to_fives() { + let cards = deck::of(DeckRule::SHORT); + assert_eq!(cards.len(), 36); + assert!(cards.iter().all(|c| c.rank >= Rank::Six), "{cards:?}"); + assert!(!cards.contains(&cs("5h")[0])); + assert!(!cards.contains(&cs("2c")[0])); +} + +#[test] +fn short_deck_has_every_suit_of_every_rank_from_six_up_exactly_once() { + let cards = deck::of(DeckRule::SHORT); + for rank in Rank::ALL.iter().filter(|r| **r >= Rank::Six) { + for suit in Suit::ALL { + assert_eq!(cards.iter().filter(|c| c.rank == *rank && c.suit == suit).count(), 1); + } + } +} + +#[test] +fn the_full_rule_is_the_old_52_card_deck_in_the_same_order() { + assert_eq!(deck::of(DeckRule::FULL), deck::full()); + assert_eq!(deck::full().len(), 52); +} + +#[test] +fn without_in_removes_dead_cards_from_the_rule_deck() { + let dead = cs("Ah Kd 6c"); + let left = deck::without_in(DeckRule::SHORT, &dead); + assert_eq!(left.len(), 33); + assert!(dead.iter().all(|c| !left.contains(c))); +} + +#[test] +fn without_in_ignores_dead_cards_that_are_not_in_the_deck() { + let left = deck::without_in(DeckRule::SHORT, &cs("5h 2c")); + assert_eq!(left.len(), 36); +} + +#[test] +fn without_in_full_matches_without() { + let dead = cs("Ah Kd 2c"); + assert_eq!(deck::without_in(DeckRule::FULL, &dead), deck::without(&dead)); +} + +#[test] +fn short_deck_draws_never_contain_cards_below_six() { + let pool = deck::of(DeckRule::SHORT); + let mut rng = Rng::seeded(2024); + for _ in 0..500 { + let (hand, next) = deck::draw(&pool, 9, rng).expect("pool is big enough"); + rng = next; + assert!(hand.iter().all(|c| c.rank >= Rank::Six), "{hand:?}"); + assert!(hand.iter().enumerate().all(|(i, c)| !hand[..i].contains(c)), "{hand:?}"); + } +} + +#[test] +fn drawing_more_than_the_short_deck_holds_is_none() { + let pool = deck::of(DeckRule::SHORT); + assert!(deck::draw(&pool, 37, Rng::seeded(1)).is_none()); + assert!(deck::draw(&pool, 36, Rng::seeded(1)).is_some()); +} diff --git a/tests/short_deck_equity.rs b/tests/short_deck_equity.rs new file mode 100644 index 00000000..18a62ef6 --- /dev/null +++ b/tests/short_deck_equity.rs @@ -0,0 +1,211 @@ +//! Short deck equity: Monte Carlo against exact enumeration of the 36-card deck. +//! +//! Reference values come from exact enumeration over the remaining 32 cards +//! (C(32,5) = 201 376 boards per heads-up matchup), evaluated with the short deck rules +//! (`judge`: flush over full house, ace low in A-6-7-8-9). Tolerance for the Monte Carlo +//! estimate: 0.006 (about 5 standard errors at 200 000 trials; the seed is fixed anyway). +//! +//! Published short deck figures could not be verified offline, so none is asserted as exact. +//! Recorded exact values (this enumeration): AA vs KK 74.26 %, AKs vs QQ 54.28 %, AKo vs JTs 49.35 %. +//! The bands below only guard against gross errors. Shape check from general knowledge: AKs is a +//! slight favourite over QQ in short deck (hold'em: about 46 %), pair over pair is a smaller +//! favourite than in hold'em (AA vs KK 81.9 %, PokerStove). +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::fault::Fault; +use pokerfreak::hand::showdown::judge; +use pokerfreak::rng::Rng; +use pokerfreak::variant::{rules, Rules, Variant}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +/// Hero's exact share against one known hand over every possible board. +fn exact_share(rules: &Rules, hero: &[Card], villain: &[Card]) -> f64 { + let dead: Vec = hero.iter().chain(villain).copied().collect(); + let pool = deck::without_in(rules.deck, &dead); + let n = pool.len(); + let (mut total, mut shares) = (0u64, 0.0f64); + let mut score = |board: [Card; 5]| { + let h = judge(rules, hero, &board).expect("hero"); + let v = judge(rules, villain, &board).expect("villain"); + total += 1; + shares += match h.cmp(&v) { + std::cmp::Ordering::Greater => 1.0, + std::cmp::Ordering::Equal => 0.5, + std::cmp::Ordering::Less => 0.0, + }; + }; + for a in 0..n { + for b in a + 1..n { + for c in b + 1..n { + for d in c + 1..n { + for e in d + 1..n { + score([pool[a], pool[b], pool[c], pool[d], pool[e]]); + } + } + } + } + } + shares / total as f64 +} + +fn mc(rules: Rules, hero: &str, board: &str, villains: &[VillainRange], trials: u32) -> Result { + let (hero, board) = (cs(hero), cs(board)); + let query = Query { rules, hero: &hero, board: &board, villains, trials }; + estimate(&query, Rng::seeded(2025)).map(|(e, _)| e) +} + +fn matchup(hero: &str, villain: &str) -> (f64, f64) { + let short = rules(Variant::ShortDeck); + let exact = exact_share(&short, &cs(hero), &cs(villain)); + let sampled = mc(short, hero, "", &[VillainRange::Exact(cs(villain))], 200_000).expect("estimate").share; + (exact, sampled) +} + +fn agrees(hero: &str, villain: &str) -> f64 { + let (exact, sampled) = matchup(hero, villain); + println!("{hero} vs {villain}: exact {exact:.5}, sampled {sampled:.5}"); + assert!((exact - sampled).abs() < 0.006, "{hero} vs {villain}: exact {exact:.4}, sampled {sampled:.4}"); + exact +} + +#[test] +fn aces_against_kings() { + let exact = agrees("Ah Ad", "Kc Ks"); + assert!((0.70..0.80).contains(&exact), "plausibility band: {exact}"); +} + +#[test] +fn ace_king_suited_against_queens() { + let exact = agrees("Ah Kh", "Qc Qs"); + assert!((0.50..0.58).contains(&exact), "plausibility band: {exact}"); +} + +#[test] +fn ace_king_offsuit_against_jack_ten_suited() { + let exact = agrees("Ah Kd", "Jc Tc"); + assert!((0.45..0.55).contains(&exact), "plausibility band: {exact}"); +} + +#[test] +fn the_two_matchup_sides_add_up_to_one() { + let short = rules(Variant::ShortDeck); + let (a, b) = (cs("Ah Ad"), cs("Kc Ks")); + let sum = exact_share(&short, &a, &b) + exact_share(&short, &b, &a); + assert!((sum - 1.0).abs() < 1e-12, "{sum}"); +} + +#[test] +fn exact_enumeration_on_a_four_card_board_is_a_hand_countable_value() { + // Hero Ah Kh vs Qc Qd on Ac 7d 6s Ts: 28 rivers left in the 36-card deck. + // Hero has a pair of aces, villain a pair of queens; only Qh or Qs (2 of 28 rivers) turn it. + let short = rules(Variant::ShortDeck); + let (hero, villain) = (cs("Ah Kh"), cs("Qc Qd")); + let board = cs("Ac 7d 6s Ts"); + let pool = deck::without_in(short.deck, &[hero.clone(), villain.clone(), board.clone()].concat()); + assert_eq!(pool.len(), 36 - 8); + let share: f64 = pool + .iter() + .map(|river| { + let full = [board.clone(), vec![*river]].concat(); + let (h, v) = (judge(&short, &hero, &full).expect("h"), judge(&short, &villain, &full).expect("v")); + f64::from(u8::from(h > v)) + 0.5 * f64::from(u8::from(h == v)) + }) + .sum::() + / pool.len() as f64; + let sampled = + mc(short, "Ah Kh", "Ac 7d 6s Ts", &[VillainRange::Exact(cs("Qc Qd"))], 20_000).expect("estimate").share; + assert!((share - sampled).abs() < 0.02, "exact {share}, sampled {sampled}"); + // Queens need Qh or Qs (2 outs) to pass aces; a river king or ace does not hurt hero. + assert!((share - 26.0 / 28.0).abs() < 1e-12, "{share}"); +} + +#[test] +fn burns_do_not_change_equity_because_burned_cards_are_unseen_random_cards() { + let short = rules(Variant::ShortDeck); + let none = Rules { burns: 0, ..short }; + let villains = [VillainRange::Any, VillainRange::Any]; + let with = mc(short, "Ah Ad", "", &villains, 5_000).expect("with burns"); + let without = mc(none, "Ah Ad", "", &villains, 5_000).expect("without burns"); + assert_eq!(with, without); +} + +#[test] +fn short_deck_runs_are_reproducible_for_one_seed() { + let short = rules(Variant::ShortDeck); + let a = mc(short, "Ah 9h", "Ac 7d 6s", &[VillainRange::Any], 4_000).expect("a"); + let b = mc(short, "Ah 9h", "Ac 7d 6s", &[VillainRange::Any], 4_000).expect("b"); + assert_eq!(a, b); +} + +#[test] +fn fourteen_two_card_players_fit_the_short_deck_fifteen_do_not() { + // 14 x 2 + 5 board + 3 burns = 36 + let short = rules(Variant::ShortDeck); + let thirteen: Vec = (0..13).map(|_| VillainRange::Any).collect(); + assert!(mc(short, "Ah Ad", "", &thirteen, 50).is_ok()); + let fourteen: Vec = (0..14).map(|_| VillainRange::Any).collect(); + assert!(matches!(mc(short, "Ah Ad", "", &fourteen, 50), Err(Fault::Exhausted(_)))); +} + +#[test] +fn known_hands_count_towards_the_short_deck_capacity() { + let short = rules(Variant::ShortDeck); + let mut villains: Vec = (0..12).map(|_| VillainRange::Any).collect(); + villains.push(VillainRange::Exact(cs("Kc Ks"))); + assert!(mc(short, "Ah Ad", "", &villains, 50).is_ok()); + villains.push(VillainRange::Exact(cs("Qc Qs"))); + assert!(matches!(mc(short, "Ah Ad", "", &villains, 50), Err(Fault::Exhausted(_)))); +} + +#[test] +fn the_full_deck_capacity_is_unchanged() { + // hold'em: 2 + 29 x 2 + 5 = 65 > 52 fails, 2 + 21 x 2 + 5 = 49 still runs (no burn reserve) + let nlhe = rules(Variant::Nlhe); + let twenty_one: Vec = (0..21).map(|_| VillainRange::Any).collect(); + assert!(mc(nlhe, "Ah Ad", "", &twenty_one, 20).is_ok()); +} + +#[test] +fn cards_outside_the_short_deck_are_invalid_input() { + let short = rules(Variant::ShortDeck); + let any = [VillainRange::Any]; + assert!(matches!(mc(short, "Ah 5h", "", &any, 50), Err(Fault::Invalid { .. }))); + assert!(matches!(mc(short, "Ah Kh", "2c 7d 8s", &any, 50), Err(Fault::Invalid { .. }))); + assert!(matches!( + mc(short, "Ah Kh", "", &[VillainRange::Exact(cs("Qc 3d"))], 50), + Err(Fault::Invalid { .. }) + )); +} + +#[test] +fn short_deck_samples_never_deal_a_card_below_six() { + // A deal with a wheel board would be a fault (judge rejects it), so 20 000 clean trials + // against 5 random hands prove that nothing below six is ever dealt. + let short = rules(Variant::ShortDeck); + let villains: Vec = (0..5).map(|_| VillainRange::Any).collect(); + let e = mc(short, "Ah Ad", "", &villains, 20_000).expect("clean run"); + assert_eq!(e.trials, 20_000); +} + +#[test] +fn holdem_results_are_bit_identical_to_before_for_the_same_seed() { + // Golden values recorded on the unchanged code before the short deck work (seed 77, 3000 trials). + let golden = |variant, hero: &str, board: &str, n: usize| { + let (h, b) = (cs(hero), cs(board)); + let vs: Vec = (0..n).map(|_| VillainRange::Any).collect(); + let query = Query { rules: rules(variant), hero: &h, board: &b, villains: &vs, trials: 3000 }; + estimate(&query, Rng::seeded(77)).expect("estimate").0 + }; + let a = golden(Variant::Nlhe, "Ah Kd", "", 2); + assert_eq!((a.win, a.tie, a.share, a.std_error), (0.4683333333333333, 0.014666666666666666, 0.4751111111111111, 0.009053331466858876)); + let b = golden(Variant::Nlhe, "Qs Qc", "7d 8h 2c", 1); + assert_eq!((b.win, b.tie, b.share, b.std_error), (0.8013333333333333, 0.0003333333333333333, 0.8015, 0.007281653638800784)); + let c = golden(Variant::Plo5, "Ah Kh Qd Jc 9s", "Th 5h 2h", 2); + assert_eq!((c.win, c.tie, c.share, c.std_error), (0.8133333333333334, 0.0, 0.8133333333333334, 0.007115074291118128)); +} diff --git a/tests/short_deck_frequencies.rs b/tests/short_deck_frequencies.rs new file mode 100644 index 00000000..840c54ba --- /dev/null +++ b/tests/short_deck_frequencies.rs @@ -0,0 +1,62 @@ +//! Complete enumeration of all C(36,5) = 376 992 five-card hands of the short deck. +//! +//! Reference: the published short deck (six-plus) five-card frequencies, Wikipedia +//! "Six-plus hold'em": straight flush 24, quads 288, flush 480, full house 1 728, +//! straight 6 120, trips 16 128, two pair 36 288, pair 193 536, high card 122 400. +//! They also follow from counting: 4 suits x 6 straights = 24 straight flushes, 9 x 32 = 288 quads, +//! 9 x 4 x 8 x 6 = 1 728 full houses, 4 x C(9,5) - 24 = 480 flushes. +//! The flush is rarer than the full house, which is why the short deck ranks it higher. +use pokerfreak::card::{deck, Card}; +use pokerfreak::hand::category::Category; +use pokerfreak::hand::five::evaluate_in; +use pokerfreak::hand::strength::Strength; +use pokerfreak::variant::{DeckRule, HandRanking}; + +fn counts(ranking: HandRanking) -> ([u32; 9], Vec) { + let cards = deck::of(DeckRule::SHORT); + let n = cards.len(); + let mut counts = [0u32; 9]; + let mut straight_flushes = Vec::new(); + for a in 0..n { + for b in a + 1..n { + for c in b + 1..n { + for d in c + 1..n { + for e in d + 1..n { + let five: [Card; 5] = [cards[a], cards[b], cards[c], cards[d], cards[e]]; + let s = evaluate_in(DeckRule::SHORT, ranking, &five); + counts[s.category as usize] += 1; + if s.category == Category::StraightFlush { + straight_flushes.push(s); + } + } + } + } + } + } + (counts, straight_flushes) +} + +#[test] +fn five_card_frequencies_match_the_published_table() { + let (counts, straight_flushes) = counts(HandRanking::FlushOverFullHouse); + assert_eq!(counts[Category::StraightFlush as usize], 24); + assert_eq!(counts[Category::FourOfAKind as usize], 288); + assert_eq!(counts[Category::Flush as usize], 480); + assert_eq!(counts[Category::FullHouse as usize], 1_728); + assert_eq!(counts[Category::Straight as usize], 6_120); + assert_eq!(counts[Category::ThreeOfAKind as usize], 16_128); + assert_eq!(counts[Category::TwoPair as usize], 36_288); + assert_eq!(counts[Category::Pair as usize], 193_536); + assert_eq!(counts[Category::HighCard as usize], 122_400); + assert_eq!(counts.iter().sum::(), 376_992); + // the lowest straight flush is the ace-low one, nine high + let lowest = straight_flushes.iter().min().expect("some"); + assert_eq!(lowest.ranks[0], 9); +} + +#[test] +fn the_ranking_choice_changes_how_hands_compare_not_what_they_are() { + let (standard, _) = counts(HandRanking::Standard); + let (flush_first, _) = counts(HandRanking::FlushOverFullHouse); + assert_eq!(standard, flush_first); +} diff --git a/tests/short_deck_guard.rs b/tests/short_deck_guard.rs new file mode 100644 index 00000000..bbd692e8 --- /dev/null +++ b/tests/short_deck_guard.rs @@ -0,0 +1,90 @@ +//! `guard::validate::check` for SHORT_DECK: cards must exist in the 36-card deck and every +//! hand (hero, live villains), the board and the burns must fit into it. +mod short_deck_spot; + +use pokerfreak::fault::Fault; +use pokerfreak::game::{Spot, Street, Villain}; +use pokerfreak::guard::validate::check; +use short_deck_spot::*; + +fn fault_text(spot: Spot) -> String { + match check(spot) { + Ok(_) => "accepted".to_string(), + Err(fault) => fault.to_string(), + } +} + +fn rejects(spot: Spot, needle: &str) { + let text = fault_text(spot); + assert!(text.contains(needle), "expected a fault mentioning {needle:?}, got {text:?}"); +} + +fn field(n: u8, folded: bool) -> Vec { + (0..n).map(|i| villain(i + 1, folded)).collect() +} + +#[test] +fn a_consistent_short_deck_spot_passes_unchanged() { + assert_eq!(check(flop()), Ok(flop())); +} + +#[test] +fn a_hero_card_below_six_is_rejected_with_a_specific_fault() { + let spot = Spot { hero_cards: cards("Ah 5h"), ..flop() }; + assert!(matches!(check(spot.clone()), Err(Fault::Invalid { .. }))); + rejects(spot, "heroCards"); + rejects(Spot { hero_cards: cards("Ah 5h"), ..flop() }, "SHORT_DECK"); + rejects(Spot { hero_cards: cards("2c Kd"), ..flop() }, "deck"); +} + +#[test] +fn a_board_card_below_six_is_rejected() { + let spot = Spot { board: cards("Ac 7d 5s"), ..flop() }; + assert!(matches!(check(spot.clone()), Err(Fault::Invalid { .. }))); + rejects(spot, "board"); +} + +#[test] +fn the_same_cards_are_fine_in_a_full_deck_variant() { + assert!(check(as_nlhe(Spot { hero_cards: cards("Ah 5h"), board: cards("Ac 7d 2s"), ..flop() })).is_ok()); +} + +#[test] +fn six_is_the_lowest_legal_rank() { + let spot = Spot { hero_cards: cards("6h 6d"), board: cards("6c 6s 7d"), ..flop() }; + assert!(check(spot).is_ok()); +} + +#[test] +fn thirteen_live_villains_fit_fourteen_do_not() { + // hero + 13 villains = 14 players x 2 + 5 board + 3 burns = 36 + assert!(check(Spot { villains: field(13, false), seats: 10, ..flop() }).is_ok()); + let spot = Spot { villains: field(14, false), seats: 10, ..flop() }; + assert!(matches!(check(spot.clone()), Err(Fault::Invalid { .. }) | Err(Fault::Inconsistent(_)))); + rejects(spot, "players"); +} + +#[test] +fn folded_villains_do_not_count_against_the_deck() { + let mut villains = field(13, false); + villains.extend(field(5, true)); + assert!(check(Spot { villains, seats: 10, ..flop() }).is_ok()); +} + +#[test] +fn the_capacity_check_also_holds_preflop() { + let spot = Spot { + street: Street::Preflop, + board: vec![], + villains: field(14, false), + seats: 10, + ..flop() + }; + rejects(spot, "players"); +} + +#[test] +fn ordinary_tables_are_untouched() { + let nine = Spot { villains: field(8, false), seats: 9, ..flop() }; + assert!(check(nine).is_ok()); +} diff --git a/tests/short_deck_percentile.rs b/tests/short_deck_percentile.rs new file mode 100644 index 00000000..36fa3750 --- /dev/null +++ b/tests/short_deck_percentile.rs @@ -0,0 +1,120 @@ +//! Preflop strength of the 81 two-card classes of the short deck (630 combos). +//! The table is ranked by all-in equity against one random short deck hand; see +//! `preflop::short_deck_ranking` for how it was produced. +use pokerfreak::card::{deck, Card}; +use pokerfreak::preflop::hand_percentile::percentile; +use pokerfreak::preflop::short_deck_percentile::short_deck_percentile; +use pokerfreak::preflop::short_deck_ranking::RANKING; +use pokerfreak::variant::{DeckRule, Variant}; + +fn hand(text: &str) -> Vec { + Card::parse_list(text).expect("valid cards") +} + +fn pct(text: &str) -> f64 { + percentile(Variant::ShortDeck, &hand(text)) +} + +fn all_combos() -> Vec> { + let cards = deck::of(DeckRule::SHORT); + (0..cards.len()) + .flat_map(|i| (i + 1..cards.len()).map(move |j| (i, j))) + .map(|(i, j)| vec![cards[i], cards[j]]) + .collect() +} + +#[test] +fn the_ranking_has_81_distinct_classes() { + assert_eq!(RANKING.len(), 81); + let mut sorted: Vec<&str> = RANKING.to_vec(); + sorted.sort_unstable(); + sorted.dedup(); + assert_eq!(sorted.len(), 81); + // 9 pairs, 36 suited, 36 offsuit + assert_eq!(RANKING.iter().filter(|c| c.len() == 2).count(), 9); + assert_eq!(RANKING.iter().filter(|c| c.ends_with('s')).count(), 36); + assert_eq!(RANKING.iter().filter(|c| c.ends_with('o')).count(), 36); +} + +#[test] +fn the_ranking_names_only_ranks_from_six_up() { + assert!(RANKING.iter().all(|c| c.chars().take(2).all(|r| "AKQJT9876".contains(r)))); +} + +#[test] +fn there_are_630_combos() { + assert_eq!(all_combos().len(), 630); +} + +#[test] +fn every_combo_gets_a_percentile_in_the_open_unit_interval_and_the_mean_is_one_half() { + let all: Vec = all_combos().iter().map(|c| short_deck_percentile(c)).collect(); + assert!(all.iter().all(|p| *p > 0.0 && *p < 1.0)); + let mean = all.iter().sum::() / all.len() as f64; + assert!((mean - 0.5).abs() < 1e-9, "{mean}"); +} + +#[test] +fn suits_inside_a_class_do_not_matter() { + assert_eq!(pct("Ah Kh"), pct("Ac Kc")); + assert_eq!(pct("Ah Kd"), pct("As Kc")); + assert_eq!(pct("Ah Ad"), pct("Ac As")); + assert_eq!(pct("Kh Ah"), pct("Ah Kh")); +} + +#[test] +fn aces_are_the_best_hand_and_the_percentile_is_combo_weighted() { + // AA is 6 of 630 combos; the middle of that block is 3/630 + assert!((pct("Ah Ad") - 3.0 / 630.0).abs() < 1e-12, "{}", pct("Ah Ad")); + assert!(pct("Ah Ad") < pct("Kh Kd")); +} + +#[test] +fn pairs_descend() { + let pairs = ["Ah Ad", "Kh Kd", "Qh Qd", "Jh Jd", "Th Td", "9h 9d", "8h 8d", "7h 7d", "6h 6d"]; + let values: Vec = pairs.iter().map(|p| pct(p)).collect(); + assert!(values.windows(2).all(|w| w[0] < w[1]), "{values:?}"); +} + +#[test] +fn suited_beats_offsuit_and_higher_beats_lower_in_the_same_shape() { + assert!(pct("Ah Kh") < pct("Ah Kd")); + assert!(pct("Ah Kh") < pct("Ah Qh")); + assert!(pct("Kh Kd") < pct("Ah Kh")); + assert!(pct("Th 9h") < pct("Th 7h")); + assert!(pct("Th 9h") < pct("Th 9d")); +} + +#[test] +fn the_weakest_hands_are_low_unconnected_offsuit_cards() { + assert_eq!(RANKING[80], "76o"); + assert!(pct("7c 6d") > 0.98, "{}", pct("7c 6d")); + assert!(pct("Ah Ad") < 0.05); + assert!(pct("6c 7d") > pct("Ah Ad")); +} + +#[test] +fn invalid_hands_are_one() { + assert_eq!(pct("Ah"), 1.0); + assert_eq!(pct(""), 1.0); + assert_eq!(pct("Ah Kd Qc"), 1.0); + assert_eq!(pct("Ah Ah"), 1.0); + assert_eq!(pct("Ah 5h"), 1.0, "a five does not exist in the short deck"); + assert_eq!(pct("2c 3d"), 1.0); + assert_eq!(pct("Ah Kd Qc Jh Th"), 1.0); +} + +#[test] +fn the_dispatch_follows_the_deck_not_the_variant_name() { + // the same two cards are valid in both decks but rank differently + let nlhe = percentile(Variant::Nlhe, &hand("Ah Ad")); + let short = percentile(Variant::ShortDeck, &hand("Ah Ad")); + assert!(nlhe < short, "AA is 6/1326 of the full deck, 6/630 of the short one: {nlhe} {short}"); + // hold'em is untouched + assert!(percentile(Variant::Nlhe, &hand("7c 2d")) > 0.93); +} + +#[test] +fn a_hand_from_the_full_deck_is_not_ranked_by_the_short_deck() { + assert_eq!(short_deck_percentile(&hand("Ah 5h")), 1.0); +} diff --git a/tests/short_deck_ranking.rs b/tests/short_deck_ranking.rs new file mode 100644 index 00000000..446ce203 --- /dev/null +++ b/tests/short_deck_ranking.rs @@ -0,0 +1,221 @@ +//! Showdown under the variant rules: category order and the low ace. +//! +//! References (published short deck / six-plus hold'em rules, Wikipedia "Six-plus hold'em", +//! and the standard ranking, Wikipedia "List of poker hands"): +//! * R1 a flush beats a full house in short deck (standard: the other way round); +//! * R2 the ace plays low in the lowest straight: A-6-7-8-9 (A-2-3-4-5 in the full deck); +//! * R3 A-2-3-4-5 cannot occur in short deck, the ranks do not exist; +//! * R4 6-7-8-9-T is the next straight above A-6-7-8-9; +//! * R5 a straight still beats three of a kind here (some rule sets swap them, ours does not). +use pokerfreak::card::Card; +use pokerfreak::fault::Fault; +use pokerfreak::hand::category::Category; +use pokerfreak::hand::showdown::{best, judge}; +use pokerfreak::hand::strength::Strength; +use pokerfreak::variant::{rules, HoleUsage, Variant}; + +fn cs(text: &str) -> Vec { + Card::parse_list(text).expect("cards") +} + +fn short(hole: &str, board: &str) -> Strength { + judge(&rules(Variant::ShortDeck), &cs(hole), &cs(board)).expect("strength") +} + +fn nlhe(hole: &str, board: &str) -> Strength { + judge(&rules(Variant::Nlhe), &cs(hole), &cs(board)).expect("strength") +} + +#[test] +fn r1_flush_beats_full_house_in_short_deck() { + let board = "Kh 7h 6h Ks 9c"; + let flush = short("Ah 8h", board); + let boat = short("Kd 7c", board); + assert_eq!(flush.category, Category::Flush); + assert_eq!(boat.category, Category::FullHouse); + assert!(flush > boat); + assert!(boat < flush); +} + +#[test] +fn r1_full_house_still_beats_flush_with_standard_rules() { + let board = "Kh 7h 6h Ks 9c"; + assert!(nlhe("Kd 7c", board) > nlhe("Ah 8h", board)); + // `best` is the standard-rules function whatever the caller thinks of the deck. + let usage = HoleUsage::BestFiveOfAll; + let flush = best(usage, &cs("Ah 8h"), &cs(board)).expect("flush"); + let boat = best(usage, &cs("Kd 7c"), &cs(board)).expect("boat"); + assert!(boat > flush); +} + +#[test] +fn a_higher_flush_beats_a_lower_one_and_a_bigger_boat_beats_a_smaller_one() { + let board = "Kh 7h 6h Ks 9c"; + assert!(short("Ah 8h", board) > short("Th 8h", board)); + let boat_board = "Kh Kd 7c 7h 9s"; + assert!(short("Ks 6c", boat_board) > short("7s 6c", boat_board)); +} + +#[test] +fn r2_ace_low_straight_is_a_nine_high_straight() { + let s = short("Ah 6c", "7d 8s 9h Kc Qd"); + assert_eq!(s.category, Category::Straight); + assert_eq!(s.ranks[0], 9); +} + +#[test] +fn r2_the_full_deck_wheel_is_unchanged() { + let s = nlhe("Ah 2c", "3d 4s 5h Kc Qd"); + assert_eq!(s.category, Category::Straight); + assert_eq!(s.ranks[0], 5); +} + +#[test] +fn r2_ace_six_seven_eight_nine_is_no_straight_in_the_full_deck() { + assert_eq!(nlhe("Ah 6c", "7d 8s 9h Kc Qd").category, Category::HighCard); +} + +#[test] +fn r3_a_wheel_cannot_exist_in_short_deck() { + let out = judge(&rules(Variant::ShortDeck), &cs("Ah 2c"), &cs("3d 4s 5h Kc Qd")); + assert!(matches!(out, Err(Fault::Invalid { .. })), "{out:?}"); + let low_card = judge(&rules(Variant::ShortDeck), &cs("Ah Kc"), &cs("Qd Js 5h")); + assert!(matches!(low_card, Err(Fault::Invalid { .. })), "{low_card:?}"); +} + +#[test] +fn ace_low_needs_all_four_cards_ace_six_seven_eight_ten_is_not_a_straight() { + assert_eq!(short("Ah 6c", "7d 8s Th Kc Qd").category, Category::HighCard); +} + +#[test] +fn r4_six_to_ten_beats_ace_to_nine() { + let board = "7d 8s 9h Kc Kd"; + let low = short("Ah 6s", board); + let next = short("Th 6c", board); + assert_eq!(low.category, Category::Straight); + assert_eq!(next.category, Category::Straight); + assert!(next > low); +} + +#[test] +fn the_broadway_straight_is_the_highest() { + let top = short("Ah Kc", "Qd Js Th 6c 7c"); + let jack_high = short("Jh Tc", "9d 8s 7h 6c Kc"); + assert_eq!(top.category, Category::Straight); + assert_eq!(top.ranks[0], 14); + assert!(top > jack_high); +} + +#[test] +fn straight_flush_ace_to_nine_suited() { + let s = short("Ah 6h", "7h 8h 9h Kc Kd"); + assert_eq!(s.category, Category::StraightFlush); + assert_eq!(s.ranks[0], 9); + // with the full-deck ladder those cards are only a flush + assert_eq!(nlhe("Ah 6h", "7h 8h 9h Kc Kd").category, Category::Flush); +} + +#[test] +fn the_lowest_straight_flush_still_beats_four_of_a_kind() { + let board = "7h 8h 9h Kc Kd"; + assert!(short("Ah 6h", board) > short("Kh Ks", board)); + assert_eq!(short("Kh Ks", board).category, Category::FourOfAKind); +} + +#[test] +fn a_ten_high_straight_flush_beats_the_ace_low_one() { + let board = "7h 8h 9h Kc Kd"; + assert!(short("Th 6h", board) > short("Ah 6h", board)); +} + +#[test] +fn r5_a_straight_beats_three_of_a_kind() { + let straight = short("Th 9d", "8c 7s 6h Kd Kc"); + let trips = short("Ah Ad", "Ac 9s 8h 6d Jc"); + assert_eq!(straight.category, Category::Straight); + assert_eq!(trips.category, Category::ThreeOfAKind); + assert!(straight > trips); +} + +#[test] +fn short_deck_category_ladder_is_flush_over_full_house_and_otherwise_standard() { + let ladder = [ + short("Ah Kd", "9c 8s 6h Td Jc"), + short("Ah Ad", "9c 8s 6h Td Jc"), + short("Ah Kd", "As Kc 8s 6h Td"), + short("Ah Ad", "Ac 9s 8h 6d Jc"), + short("Th 9d", "8c 7s 6h Kd Kc"), + short("Ah Ad", "Ac Ks Kd 9c 7h"), + short("Ah 9h", "Kh 7h 6h Qs Jd"), + short("Ah Ad", "Ac As 9s 7h 6d"), + short("Th 9h", "8h 7h 6h Ks Kd"), + ]; + let categories: Vec = ladder.iter().map(|s| s.category).collect(); + assert_eq!( + categories, + [ + Category::HighCard, + Category::Pair, + Category::TwoPair, + Category::ThreeOfAKind, + Category::Straight, + Category::FullHouse, + Category::Flush, + Category::FourOfAKind, + Category::StraightFlush, + ] + ); + assert!(ladder.windows(2).all(|w| w[0] < w[1]), "{ladder:?}"); +} + +#[test] +fn the_comparison_is_antisymmetric_and_transitive_over_a_ladder() { + let a = short("Ah 8h", "Kh 7h 6h Ks 9c"); // flush + let b = short("Kd 7c", "Kh 7h 6h Ks 9c"); // full house + let c = short("Th 9d", "8c 7s 6h Kd Kc"); // straight + assert!(a > b && b > c && a > c); + assert!(b.partial_cmp(&a) == Some(std::cmp::Ordering::Less)); +} + +#[test] +fn equal_strength_means_a_split_pot() { + let board = "Qh Jd 9c 8s 6h"; + assert_eq!(short("Ah Kd", board), short("Ac Ks", board)); +} + +#[test] +fn the_board_playing_splits_even_with_the_ace_low_straight() { + let board = "Ah 6c 7d 8s 9h"; + assert_eq!(short("Kc Kd", board), short("Qc Qd", board)); +} + +#[test] +fn kicker_comparison_is_unchanged_by_the_short_deck() { + let board = "Ad 8c 7h 6s Th"; + assert!(short("Ah Kc", board) > short("As Qc", board)); +} + +#[test] +fn omaha_rules_through_judge_are_unchanged() { + let plo = rules(Variant::Plo5); + let hole = cs("Ah Kh Qd Jc 9s"); + let board = cs("Th 5h 2h Kc 3d"); + assert_eq!(judge(&plo, &hole, &board), best(HoleUsage::ExactlyTwoHole, &hole, &board)); +} + +#[test] +fn judge_with_the_standard_rules_equals_best() { + let hole = cs("Ah Kh"); + let board = cs("Qh Jh Th 2c 3d"); + assert_eq!( + judge(&rules(Variant::Nlhe), &hole, &board), + best(HoleUsage::BestFiveOfAll, &hole, &board) + ); +} + +#[test] +fn duplicates_are_still_inconsistent_in_short_deck() { + let out = judge(&rules(Variant::ShortDeck), &cs("Ah Ah"), &cs("7d 8s 9h")); + assert!(matches!(out, Err(Fault::Inconsistent(_))), "{out:?}"); +} diff --git a/tests/short_deck_ranking_generate.rs b/tests/short_deck_ranking_generate.rs new file mode 100644 index 00000000..42fab770 --- /dev/null +++ b/tests/short_deck_ranking_generate.rs @@ -0,0 +1,61 @@ +//! Offline generator of `preflop::short_deck_ranking::RANKING` (ignored by default). +//! +//! Run: `cargo test --release --test short_deck_ranking_generate -- --ignored --nocapture` +//! It prints the table body, classes best first. Method: for every one of the 81 classes take one +//! representative hand (suits do not matter inside a class by symmetry), deal 10 000 000 seeded +//! Monte Carlo trials against one uniformly random short deck hand with a random 5-card board +//! (`equity::monte_carlo::estimate`, short deck rules: flush over full house, ace low in A-6-7-8-9), +//! rank by pot share (ties split). Seeds are the class index, so the output is reproducible. +use pokerfreak::card::Card; +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}; + +const RANKS: [char; 9] = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6']; +const TRIALS: u32 = 10_000_000; + +fn classes() -> Vec<(String, String)> { + let mut out = Vec::new(); + for (i, high) in RANKS.iter().enumerate() { + for (j, low) in RANKS.iter().enumerate().skip(i) { + if i == j { + out.push((format!("{high}{low}"), format!("{high}h {low}d"))); + } else { + out.push((format!("{high}{low}s"), format!("{high}h {low}h"))); + out.push((format!("{high}{low}o"), format!("{high}h {low}d"))); + } + } + } + out +} + +fn share_of(index: usize, hand: &str) -> f64 { + let hole = Card::parse_list(hand).expect("cards"); + let query = Query { + rules: rules(Variant::ShortDeck), + hero: &hole, + board: &[], + villains: &[VillainRange::Any], + trials: TRIALS, + }; + estimate(&query, Rng::seeded(1_000 + index as u64)).expect("estimate").0.share +} + +#[test] +#[ignore = "offline generator: prints the ranking table"] +fn print_the_ranking() { + let classes = classes(); + assert_eq!(classes.len(), 81); + let mut scored: Vec<(String, f64)> = std::thread::scope(|scope| { + let handles: Vec<_> = classes + .iter() + .enumerate() + .map(|(i, (name, hand))| scope.spawn(move || (name.clone(), share_of(i, hand)))) + .collect(); + handles.into_iter().filter_map(|h| h.join().ok()).collect() + }); + scored.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + scored.iter().for_each(|(name, share)| println!("RANK {name} {share:.5}")); +} diff --git a/tests/short_deck_sizing.rs b/tests/short_deck_sizing.rs new file mode 100644 index 00000000..773d2499 --- /dev/null +++ b/tests/short_deck_sizing.rs @@ -0,0 +1,106 @@ +//! SHORT_DECK uses the no-limit sizing rule: `allowedSizes` and the min/max bounds are enforced +//! exactly as for NLHE. Every check runs on both variants with the same chips, and the results +//! must agree (differential), plus the absolute bounds. +mod short_deck_spot; + +use pokerfreak::game::{ActionKind, Choice, Decision, Spot}; +use pokerfreak::guard::enforce::enforce; +use pokerfreak::sizing::allowed::valid_allowed; +use pokerfreak::sizing::all_in::all_in; +use pokerfreak::sizing::bounds::bounds; +use pokerfreak::sizing::candidates::candidates; +use pokerfreak::sizing::fit::fit; +use pokerfreak::variant::{rules, SizingRule, Variant}; +use short_deck_spot::*; + +fn choose(spot: &Spot, choice: Choice) -> Choice { + enforce(spot, Decision::new(choice, 0.9, "test")).choice +} + +fn spots() -> Vec { + vec![ + flop(), + Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }, + Spot { allowed_sizes: Some(vec![4.6, 5.0]), ..flop() }, + Spot { max_raise_to: Some(1.0), ..flop() }, + Spot { hero_stack: 0.3, ..flop() }, + Spot { hero_stack: 0.0, ..flop() }, + Spot { min_raise_to: None, max_raise_to: None, ..flop() }, + ] +} + +#[test] +fn the_rules_table_uses_no_limit_for_short_deck() { + assert_eq!(rules(Variant::ShortDeck).sizing, SizingRule::NoLimit); +} + +#[test] +fn candidates_bounds_and_all_in_agree_with_nlhe() { + for spot in spots() { + let nlhe = as_nlhe(spot.clone()); + assert_eq!(candidates(&spot), candidates(&nlhe)); + assert_eq!(bounds(&spot), bounds(&nlhe)); + assert_eq!(all_in(&spot), all_in(&nlhe)); + assert_eq!(valid_allowed(&spot), valid_allowed(&nlhe)); + for target in [0.01, 0.5, 1.0, 1.15, 3.0, 100.0] { + assert_eq!(fit(&spot, target), fit(&nlhe, target), "target {target}"); + } + } +} + +#[test] +fn enforcement_agrees_with_nlhe_for_every_kind_of_choice() { + let choices = [ + Choice::Fold, + Choice::Call, + Choice::Raise { to: 0.01 }, + Choice::Raise { to: 1.0 }, + Choice::Raise { to: 1.15 }, + Choice::Raise { to: 100.0 }, + Choice::Raise { to: f64::NAN }, + ]; + for spot in spots() { + for choice in choices { + assert_eq!(choose(&spot, choice), choose(&as_nlhe(spot.clone()), choice), "{choice:?}"); + } + } +} + +#[test] +fn raises_snap_to_allowed_sizes_verbatim() { + let spot = Spot { allowed_sizes: Some(vec![0.5, 1.15, 4.6]), ..flop() }; + assert_eq!(choose(&spot, Choice::Raise { to: 1.15 }), Choice::Raise { to: 1.15 }); + assert_eq!(choose(&spot, Choice::Raise { to: 4.6 }), Choice::Raise { to: 1.15 }); // stack is 2.4 + assert_eq!(choose(&spot, Choice::Raise { to: 0.1 }), Choice::Raise { to: 0.5 }); + let unaffordable = Spot { allowed_sizes: Some(vec![4.6, 5.0]), ..flop() }; + assert_eq!(choose(&unaffordable, Choice::Raise { to: 4.6 }), Choice::Abstain); +} + +#[test] +fn free_raises_are_clamped_to_min_max_and_stack() { + let spot = flop(); + assert_eq!(choose(&spot, Choice::Raise { to: 100.0 }), Choice::Raise { to: 2.4 }); + assert_eq!(choose(&spot, Choice::Raise { to: 0.01 }), Choice::Raise { to: 0.5 }); + let capped = Spot { max_raise_to: Some(1.0), ..flop() }; + assert_eq!(choose(&capped, Choice::Raise { to: 2.0 }), Choice::Raise { to: 1.0 }); +} + +#[test] +fn every_candidate_lies_inside_the_bounds_and_the_stack() { + let spot = round(); + let sizes = candidates(&spot); + assert!(sizes.len() >= 2, "{sizes:?}"); + assert!(sizes.iter().all(|s| *s >= 10.0 && *s <= 100.0), "{sizes:?}"); + // NoLimit is not capped at the pot: the jam is the full stack + assert_eq!(all_in(&spot), Some(100.0)); +} + +fn round() -> Spot { + Spot { pot: 10.0, to_call: 5.0, hero_stack: 100.0, min_raise_to: Some(10.0), max_raise_to: Some(100.0), ..flop() } +} + +#[test] +fn a_raise_that_is_not_legal_is_never_returned() { + let no_raise = Spot { legal: vec![ActionKind::Fold, ActionKind::Call], ..flop() }; + assert_eq!(choose(&no_raise, Choice::Raise { to: 1.0 }), Choice::Abstain); +} diff --git a/tests/short_deck_spot/mod.rs b/tests/short_deck_spot/mod.rs new file mode 100644 index 00000000..dbe1baf3 --- /dev/null +++ b/tests/short_deck_spot/mod.rs @@ -0,0 +1,45 @@ +#![allow(dead_code)] +//! Short deck spots: the NLHE fixture with cards that exist in a 36-card deck. + +use pokerfreak::card::Card; +use pokerfreak::game::{Spot, Street, Villain}; +use pokerfreak::variant::Variant; + +pub fn cards(text: &str) -> Vec { + Card::parse_list(text).expect("fixture cards") +} + +pub fn villain(seat: u8, folded: bool) -> Villain { + Villain { seat, stack: 10.0, folded, profile: None } +} + +/// SHORT_DECK flop, hero Ah9h on Ac7d6s: same chips as the NLHE fixture +/// (pot 1.25, 0.2 to call, stack 2.4, raise bounds 0.5 ..= 20). +pub fn flop() -> Spot { + use pokerfreak::game::ActionKind::{Call, Fold, Raise}; + Spot { + variant: Variant::ShortDeck, + big_blind: 0.1, + seats: 6, + hero_seat: 5, + button_seat: None, + hero_cards: cards("Ah 9h"), + board: cards("Ac 7d 6s"), + street: Street::Flop, + pot: 1.25, + to_call: 0.2, + hero_stack: 2.4, + min_raise_to: Some(0.5), + max_raise_to: Some(20.0), + legal: vec![Fold, Call, Raise], + allowed_sizes: None, + villains: vec![villain(2, false)], + seed: 1, + history: Vec::new(), + } +} + +/// The same spot played as NLHE (cards stay legal in both decks). +pub fn as_nlhe(spot: Spot) -> Spot { + Spot { variant: Variant::Nlhe, ..spot } +}