Merge feat/shortdeck

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 12:44:23 +01:00
co-authored by Claude Opus 5.5
24 changed files with 1255 additions and 33 deletions
+15 -2
View File
@@ -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<Card> {
(0..52).filter_map(Card::from_index).collect()
of(DeckRule::FULL)
}
pub fn without(dead: &[Card]) -> Vec<Card> {
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<Card> {
(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<Card> {
of(rule).into_iter().filter(|c| !dead.contains(c)).collect()
}
/// Draws `count` distinct cards from `pool` (partial Fisher–Yates on a private copy).
+27
View File
@@ -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()
}
+1
View File
@@ -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;
+4 -4
View File
@@ -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,
+6 -2
View File
@@ -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<Vec<Card>, 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())));
}
+30
View File
@@ -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<Spot, Fault> {
cards(&spot)?;
outside_deck(&spot)?;
players_fit(&spot)?;
chips(&spot)?;
actions(&spot)?;
Ok(spot)
+15 -5
View File
@@ -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<u8> {
/// 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<u8> {
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,
}
+1
View File
@@ -2,6 +2,7 @@
pub mod category;
pub mod five;
pub mod ranking_order;
pub mod showdown;
pub mod strength;
pub mod subset;
+18
View File
@@ -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]
}
+36 -12
View File
@@ -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<Strength, Fault> {
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<Strength, Fault> {
fn select(
usage: HoleUsage,
eval: &dyn Fn(&[Card; 5]) -> Strength,
hole: &[Card],
board: &[Card],
) -> Result<Strength, Fault> {
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<Strength, Fault> {
let all: Vec<Card> = 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<Strength, Fault> {
fn exactly_two(eval: &dyn Fn(&[Card; 5]) -> Strength, hole: &[Card], board: &[Card]) -> Result<Strength, Fault> {
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<Strength, Fault> {
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<Card> {
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<Strength, Fault> {
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)
}
+13 -3
View File
@@ -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 }
}
}
+9 -5
View File
@@ -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,
}
}
+2
View File
@@ -24,3 +24,5 @@ pub mod reason;
pub mod seat_position;
pub mod situation;
pub mod width_factor;
pub mod short_deck_percentile;
pub mod short_deck_ranking;
+68
View File
@@ -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,
}
}
+19
View File
@@ -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",
];