Das Trace-Werkzeug (sim::table) spielt jeden Deal blind gegen Oracle auf gleichen Seeds und schreibt die erste divergente Hero-Entscheidung zu. Damit ist der Nit-Full-Read-Leak lokalisiert: nicht Under-Barrel, sondern das Gegenteil - der Read macht aus Flop-Checks Bluff-Raises (140 Haende, -436 bb), die mehrstraessig in genutzte Ranges bluten. Die read_gate-Doku nennt jetzt den gemessenen Mechanismus. Der Frozen-Benchmark beweist das Werkzeug verhaltensneutral (GESAMT 0.00, 0 Haende geaendert). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
495 lines
18 KiB
Rust
495 lines
18 KiB
Rust
//! One hand of No-Limit Hold'em at a table of 2-10 seats: the engine on one seat, a fixed
|
|
//! opponent on all others. Seat 1 is the button; heads-up the button posts the small blind.
|
|
//! Big blind 1, small blind 0.5, everybody starts with `stack_bb`. Rake and antes come from
|
|
//! `TableCost`; `play_hand` is the free table. The rake leaves the table: the players' results
|
|
//! then sum to minus the rake. Antes are dead money in the pot and no part of a street's bet.
|
|
|
|
use super::luck;
|
|
use super::memory::SessionMemory;
|
|
use super::opponent::{Act, Opponent, View};
|
|
use super::reader::{strength, Reading};
|
|
use crate::card::{deck, Card};
|
|
use crate::engine::decide::decide;
|
|
use crate::exploit::profile::Profile;
|
|
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
|
|
use crate::guard::validate::check;
|
|
use crate::hand::showdown::best;
|
|
use crate::rake::{split_over_pots, uncalled, HandEnd, RakeRule, MEASURED_ANTE_BB};
|
|
use crate::rng::Rng;
|
|
use crate::variant::{HoleUsage, Variant};
|
|
|
|
const SMALL_BLIND: f64 = 0.5;
|
|
const BIG_BLIND: f64 = 1.0;
|
|
const EPS: f64 = 1e-9;
|
|
|
|
/// What a table takes besides the blinds.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct TableCost {
|
|
/// Per player, in big blinds.
|
|
pub ante_bb: f64,
|
|
pub rake: Option<RakeRule>,
|
|
}
|
|
|
|
impl TableCost {
|
|
pub const FREE: TableCost = TableCost { ante_bb: 0.0, rake: None };
|
|
/// The table measured in `rake`: ante 0.16 bb, 5 % capped at 1 bb.
|
|
pub const MEASURED: TableCost = TableCost { ante_bb: MEASURED_ANTE_BB, rake: Some(RakeRule::MEASURED_BB) };
|
|
}
|
|
|
|
/// Cards for one hand: `holes[seat - 1]` and the full board in deal order.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct Deal {
|
|
pub holes: Vec<[Card; 2]>,
|
|
pub board: [Card; 5],
|
|
}
|
|
|
|
pub fn deal(players: usize, rng: Rng) -> (Deal, Rng) {
|
|
let (cards, rng) = deck::draw(&deck::full(), 2 * players + 5, rng).expect("at most 10 players");
|
|
let holes = cards.chunks(2).take(players).map(|c| [c[0], c[1]]).collect();
|
|
let board = cards[2 * players..].try_into().expect("five board cards");
|
|
(Deal { holes, board }, rng)
|
|
}
|
|
|
|
/// The read handed to the engine for a hand. `Oracle` derives the opponent's converged profile
|
|
/// (`sim::reads`); `Given` hands an exact read - `None` is blind, `Some` is the memory's snapshot.
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub enum HandRead {
|
|
Oracle,
|
|
Given(Option<Profile>),
|
|
}
|
|
|
|
pub struct HandSetup<'a> {
|
|
pub deal: &'a Deal,
|
|
pub hero_seat: u8,
|
|
pub opponent: Opponent,
|
|
pub stack_bb: f64,
|
|
/// Seeds the opponents' choices and the engine's `seed` field.
|
|
pub seed: u64,
|
|
/// The read the engine gets for this hand. See `HandRead`.
|
|
pub read: HandRead,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct HandResult {
|
|
/// Hero's result in big blinds.
|
|
pub hero_net: f64,
|
|
pub hero_decisions: u32,
|
|
/// Hero answered ABSTAIN; the table then checks, or folds when there is a price.
|
|
pub abstains: u32,
|
|
/// Requests the guard refused: a simulator bug, must stay 0.
|
|
pub invalid: u32,
|
|
/// Sum of all players' results plus the rake; must be 0.
|
|
pub chips_lost: f64,
|
|
/// Rake of the hand, big blinds.
|
|
pub rake: f64,
|
|
/// What the board cards decided (see `sim::luck`); expectation 0.
|
|
pub luck: f64,
|
|
}
|
|
|
|
/// One hero decision, for diagnostics only (`play_hand_traced`): the spot the engine faced and what
|
|
/// it answered. Never recorded on the hot `play_hand_tracked` path (trace `None`).
|
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
pub struct Dec {
|
|
pub street: Street,
|
|
pub pot: f64,
|
|
pub to_call: f64,
|
|
pub choice: Choice,
|
|
pub equity: Option<f64>,
|
|
}
|
|
|
|
struct Table<'a> {
|
|
setup: &'a HandSetup<'a>,
|
|
cost: TableCost,
|
|
hero: usize,
|
|
stack: Vec<f64>,
|
|
bet: Vec<f64>,
|
|
total: Vec<f64>,
|
|
folded: Vec<bool>,
|
|
street: Street,
|
|
max_bet: f64,
|
|
last_raise: f64,
|
|
history: Vec<ActionRecord>,
|
|
rng: Rng,
|
|
result: HandResult,
|
|
/// `Some` only for `play_hand_traced`: one `Dec` per hero decision.
|
|
trace: Option<Vec<Dec>>,
|
|
}
|
|
|
|
impl Table<'_> {
|
|
fn players(&self) -> usize {
|
|
self.stack.len()
|
|
}
|
|
|
|
/// Hero's expected share of the current pot with `cards` board cards known.
|
|
fn value(&self, cards: usize) -> f64 {
|
|
if self.folded[self.hero] {
|
|
return 0.0;
|
|
}
|
|
let live: Vec<usize> = (0..self.players()).filter(|i| !self.folded[*i]).collect();
|
|
let holes: Vec<[Card; 2]> = live.iter().map(|i| self.setup.deal.holes[*i]).collect();
|
|
let hero = live.iter().position(|i| *i == self.hero).expect("hero is live");
|
|
let dead: Vec<Card> = self.setup.deal.holes.iter().flatten().copied().collect();
|
|
let rng = Rng::seeded(self.setup.seed ^ 0x1C0C_u64.wrapping_mul(cards as u64 + 1));
|
|
let pot: f64 = self.total.iter().sum();
|
|
pot * luck::share(&holes, hero, &self.setup.deal.board[..cards], &dead, rng)
|
|
}
|
|
|
|
/// Luck of dealing the cards of `street`: value after them minus its expectation before.
|
|
fn luck_of(&mut self, street: Street) {
|
|
let before = self.street.board_len();
|
|
self.result.luck += self.value(street.board_len()) - self.value(before);
|
|
}
|
|
|
|
fn live(&self) -> usize {
|
|
self.folded.iter().filter(|f| !**f).count()
|
|
}
|
|
|
|
fn can_act(&self, i: usize) -> bool {
|
|
!self.folded[i] && self.stack[i] > EPS
|
|
}
|
|
|
|
fn record(&mut self, i: usize, action: SeenAction, amount: Option<f64>) {
|
|
self.history.push(ActionRecord { street: self.street, seat: i as u8 + 1, action, amount });
|
|
}
|
|
|
|
fn put(&mut self, i: usize, amount: f64) {
|
|
let amount = amount.min(self.stack[i]);
|
|
self.stack[i] -= amount;
|
|
self.bet[i] += amount;
|
|
self.total[i] += amount;
|
|
}
|
|
|
|
/// Dead money: in the pot, not in the street's bet.
|
|
fn post_ante(&mut self, i: usize, amount: f64) {
|
|
let amount = amount.min(self.stack[i]);
|
|
self.stack[i] -= amount;
|
|
self.total[i] += amount;
|
|
self.record(i, SeenAction::PostAnte, Some(amount));
|
|
}
|
|
|
|
fn post(&mut self, i: usize, amount: f64, action: SeenAction) {
|
|
self.put(i, amount);
|
|
self.record(i, action, Some(self.bet[i]));
|
|
}
|
|
|
|
/// Raise bounds for player `i`, or `None` when raising is impossible or pointless.
|
|
fn raise_bounds(&self, i: usize) -> Option<(f64, f64)> {
|
|
let to_call = self.max_bet - self.bet[i];
|
|
let others = (0..self.players()).any(|j| j != i && self.can_act(j));
|
|
let max = self.bet[i] + self.stack[i];
|
|
(others && self.stack[i] > to_call + EPS)
|
|
.then(|| ((self.max_bet + self.last_raise).min(max), max))
|
|
}
|
|
|
|
fn view(&self, i: usize) -> View {
|
|
let bounds = self.raise_bounds(i);
|
|
View {
|
|
to_call: (self.max_bet - self.bet[i]).min(self.stack[i]),
|
|
min_raise_to: bounds.map(|b| b.0),
|
|
max_raise_to: bounds.map(|b| b.1),
|
|
}
|
|
}
|
|
|
|
fn spot(&self, view: View) -> Spot {
|
|
let i = self.hero;
|
|
let mut legal = vec![ActionKind::Fold];
|
|
legal.push(if view.to_call > 0.0 { ActionKind::Call } else { ActionKind::Check });
|
|
if view.min_raise_to.is_some() {
|
|
legal.push(ActionKind::Raise);
|
|
}
|
|
// The engine sees the opponents the way a converged HUD would (`sim::reads`), so the ladder
|
|
// measures the exploit brain instead of playing it blind - unless the scenario hands a
|
|
// different read (blind = no profile, or the memory's snapshot).
|
|
let read = match self.setup.read {
|
|
HandRead::Oracle => super::reads::opponent_profile(self.setup.opponent),
|
|
HandRead::Given(p) => p,
|
|
};
|
|
let villains = (0..self.players())
|
|
.filter(|j| *j != i)
|
|
.map(|j| Villain { seat: j as u8 + 1, stack: self.stack[j], folded: self.folded[j], profile: read })
|
|
.collect();
|
|
let decision_seed = self.setup.seed ^ (self.result.hero_decisions as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);
|
|
Spot {
|
|
variant: Variant::Nlhe,
|
|
big_blind: BIG_BLIND,
|
|
seats: self.players() as u8,
|
|
hero_seat: i as u8 + 1,
|
|
button_seat: Some(1),
|
|
hero_cards: self.setup.deal.holes[i].to_vec(),
|
|
board: self.setup.deal.board[..self.street.board_len()].to_vec(),
|
|
street: self.street,
|
|
pot: self.total.iter().sum(),
|
|
to_call: view.to_call,
|
|
hero_stack: self.stack[i],
|
|
min_raise_to: view.min_raise_to,
|
|
max_raise_to: view.max_raise_to,
|
|
legal,
|
|
allowed_sizes: None,
|
|
villains,
|
|
seed: decision_seed,
|
|
history: self.history.clone(),
|
|
}
|
|
}
|
|
|
|
fn hero_act(&mut self, view: View) -> Act {
|
|
self.result.hero_decisions += 1;
|
|
let choice = match check(self.spot(view)) {
|
|
Ok(spot) => {
|
|
let decision = decide(&spot);
|
|
if let Some(trace) = self.trace.as_mut() {
|
|
trace.push(Dec {
|
|
street: spot.street,
|
|
pot: spot.pot,
|
|
to_call: spot.to_call,
|
|
choice: decision.choice,
|
|
equity: decision.equity,
|
|
});
|
|
}
|
|
decision.choice
|
|
}
|
|
Err(_) => {
|
|
self.result.invalid += 1;
|
|
Choice::Abstain
|
|
}
|
|
};
|
|
match choice {
|
|
Choice::Fold if view.to_call > 0.0 => Act::Fold,
|
|
Choice::Fold | Choice::Check => Act::Check,
|
|
Choice::Call => Act::Call,
|
|
Choice::Raise { to } => Act::RaiseTo(to),
|
|
Choice::Abstain => {
|
|
self.result.abstains += 1;
|
|
if view.to_call > 0.0 { Act::Fold } else { Act::Check }
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What a reading opponent knows. Its own seed, so that it does not depend on hero's play.
|
|
fn reading(&self, i: usize) -> Reading {
|
|
let board = &self.setup.deal.board[..self.street.board_len()];
|
|
let seed = self.setup.seed ^ ((i as u64 + 1) << 32) ^ (self.street.board_len() as u64 + 1).wrapping_mul(0x51_7CC1);
|
|
Reading {
|
|
strength: strength(&self.setup.deal.holes[i], board, Rng::seeded(seed)),
|
|
pot: self.total.iter().sum(),
|
|
own_bet: self.bet[i],
|
|
preflop: self.street == Street::Preflop,
|
|
}
|
|
}
|
|
|
|
fn act(&mut self, i: usize) -> bool {
|
|
let view = self.view(i);
|
|
let act = if i == self.hero {
|
|
self.hero_act(view)
|
|
} else {
|
|
let (act, rng) = match self.setup.opponent {
|
|
Opponent::Reader(style) => style.act(view, self.reading(i), self.rng),
|
|
blind => blind.act(view, self.rng),
|
|
};
|
|
self.rng = rng;
|
|
act
|
|
};
|
|
match act {
|
|
Act::Fold => {
|
|
self.folded[i] = true;
|
|
self.record(i, SeenAction::Fold, None);
|
|
false
|
|
}
|
|
Act::Check | Act::Call if view.to_call <= 0.0 => {
|
|
self.record(i, SeenAction::Check, None);
|
|
false
|
|
}
|
|
Act::Check | Act::Call => {
|
|
self.put(i, view.to_call);
|
|
let seen = if self.stack[i] <= EPS { SeenAction::AllIn } else { SeenAction::Call };
|
|
self.record(i, seen, Some(self.bet[i]));
|
|
false
|
|
}
|
|
Act::RaiseTo(to) => {
|
|
let Some((min, max)) = view.min_raise_to.zip(view.max_raise_to) else {
|
|
return self.act_passive(i, view);
|
|
};
|
|
let to = to.clamp(min, max);
|
|
let increment = to - self.max_bet;
|
|
self.put(i, to - self.bet[i]);
|
|
self.last_raise = self.last_raise.max(increment);
|
|
let opened = self.max_bet <= EPS;
|
|
self.max_bet = to;
|
|
let seen = match (self.stack[i] <= EPS, opened) {
|
|
(true, _) => SeenAction::AllIn,
|
|
(false, true) => SeenAction::Bet,
|
|
(false, false) => SeenAction::Raise,
|
|
};
|
|
self.record(i, seen, Some(self.bet[i]));
|
|
true
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A raise where none is possible counts as check or call.
|
|
fn act_passive(&mut self, i: usize, view: View) -> bool {
|
|
if view.to_call > 0.0 {
|
|
self.put(i, view.to_call);
|
|
let seen = if self.stack[i] <= EPS { SeenAction::AllIn } else { SeenAction::Call };
|
|
self.record(i, seen, Some(self.bet[i]));
|
|
} else {
|
|
self.record(i, SeenAction::Check, None);
|
|
}
|
|
false
|
|
}
|
|
|
|
/// One betting round from `first`. Stops early when only one player is left.
|
|
fn round(&mut self, first: usize) {
|
|
let n = self.players();
|
|
let actors = (0..n).filter(|i| self.can_act(*i)).count();
|
|
let owes = (0..n).any(|i| self.can_act(i) && self.bet[i] + EPS < self.max_bet);
|
|
if actors < 2 && !owes {
|
|
return;
|
|
}
|
|
let mut pending: Vec<bool> = (0..n).map(|i| self.can_act(i)).collect();
|
|
let mut i = first;
|
|
while self.live() > 1 && pending.iter().any(|p| *p) {
|
|
if pending[i] {
|
|
pending[i] = false;
|
|
if self.act(i) {
|
|
for (j, p) in pending.iter_mut().enumerate() {
|
|
*p = j != i && !self.folded[j] && self.stack[j] > EPS;
|
|
}
|
|
}
|
|
}
|
|
i = (i + 1) % n;
|
|
}
|
|
}
|
|
|
|
fn next_street(&mut self, street: Street) {
|
|
self.street = street;
|
|
self.bet.iter_mut().for_each(|b| *b = 0.0);
|
|
self.max_bet = 0.0;
|
|
self.last_raise = BIG_BLIND;
|
|
}
|
|
|
|
/// Side pots level by level; ties split evenly. Returns everybody's winnings and the rake.
|
|
fn showdown(&self) -> (Vec<f64>, f64) {
|
|
let n = self.players();
|
|
let mut won = vec![0.0; n];
|
|
let mut left = self.total.clone();
|
|
if let Some((top, amount)) = uncalled(&left) {
|
|
left[top] -= amount;
|
|
won[top] += amount;
|
|
}
|
|
let strength: Vec<_> = (0..n)
|
|
.map(|i| {
|
|
(!self.folded[i]).then(|| {
|
|
best(HoleUsage::BestFiveOfAll, &self.setup.deal.holes[i], &self.setup.deal.board)
|
|
.expect("valid deal")
|
|
})
|
|
})
|
|
.collect();
|
|
let mut pots: Vec<(f64, Vec<usize>)> = Vec::new();
|
|
loop {
|
|
let contenders: Vec<usize> = (0..n).filter(|i| !self.folded[*i] && left[*i] > EPS).collect();
|
|
let Some(level) = contenders.iter().map(|i| left[*i]).min_by(f64::total_cmp) else {
|
|
break;
|
|
};
|
|
let pot: f64 = left.iter_mut().map(|l| {
|
|
let part = l.min(level);
|
|
*l -= part;
|
|
part
|
|
}).sum();
|
|
let top = contenders.iter().filter_map(|i| strength[*i]).max().expect("a contender");
|
|
pots.push((pot, contenders.into_iter().filter(|i| strength[*i] == Some(top)).collect()));
|
|
}
|
|
let sizes: Vec<f64> = pots.iter().map(|(pot, _)| *pot).collect();
|
|
let rake = self.rake_of(sizes.iter().sum());
|
|
for ((pot, winners), taken) in pots.iter().zip(split_over_pots(rake, &sizes)) {
|
|
for w in winners {
|
|
won[*w] += (pot - taken) / winners.len() as f64;
|
|
}
|
|
}
|
|
(won, rake)
|
|
}
|
|
|
|
fn rake_of(&self, pot: f64) -> f64 {
|
|
let end = if self.street == Street::Preflop { HandEnd::NoFlop } else { HandEnd::FlopDealt };
|
|
self.cost.rake.map_or(0.0, |rule| rule.of_hand(pot, self.live(), end))
|
|
}
|
|
}
|
|
|
|
impl<'a> Table<'a> {
|
|
fn new(setup: &'a HandSetup<'a>, cost: TableCost, trace: Option<Vec<Dec>>) -> Table<'a> {
|
|
let n = setup.deal.holes.len();
|
|
Table {
|
|
setup,
|
|
cost,
|
|
hero: setup.hero_seat as usize - 1,
|
|
stack: vec![setup.stack_bb; n],
|
|
bet: vec![0.0; n],
|
|
total: vec![0.0; n],
|
|
folded: vec![false; n],
|
|
street: Street::Preflop,
|
|
max_bet: BIG_BLIND,
|
|
last_raise: BIG_BLIND,
|
|
history: Vec::new(),
|
|
rng: Rng::seeded(setup.seed),
|
|
result: HandResult { hero_net: 0.0, hero_decisions: 0, abstains: 0, invalid: 0, chips_lost: 0.0, rake: 0.0, luck: 0.0 },
|
|
trace,
|
|
}
|
|
}
|
|
|
|
/// Antes, blinds, every betting round, showdown, and hero's net. The whole hand.
|
|
fn run(&mut self) {
|
|
let n = self.players();
|
|
if self.cost.ante_bb > 0.0 {
|
|
for i in 0..n {
|
|
self.post_ante(i, self.cost.ante_bb);
|
|
}
|
|
}
|
|
let (sb, bb) = if n == 2 { (0, 1) } else { (1, 2) };
|
|
self.post(sb, SMALL_BLIND, SeenAction::PostSmallBlind);
|
|
self.post(bb, BIG_BLIND, SeenAction::PostBigBlind);
|
|
self.round((bb + 1) % n);
|
|
for street in [Street::Flop, Street::Turn, Street::River] {
|
|
if self.live() < 2 {
|
|
break;
|
|
}
|
|
self.luck_of(street);
|
|
self.next_street(street);
|
|
self.round(1 % n);
|
|
}
|
|
let (won, rake) = self.showdown();
|
|
let nets: Vec<f64> = (0..n).map(|i| self.stack[i] + won[i] - self.setup.stack_bb).collect();
|
|
self.result.hero_net = nets[self.hero];
|
|
self.result.rake = rake;
|
|
self.result.chips_lost = nets.iter().sum::<f64>() + rake;
|
|
}
|
|
}
|
|
|
|
/// Plays one hand at the free table and reports hero's result.
|
|
pub fn play_hand(setup: &HandSetup) -> HandResult {
|
|
play_hand_at(setup, TableCost::FREE)
|
|
}
|
|
|
|
/// Plays one hand to the end at a table with `cost` and reports hero's result.
|
|
pub fn play_hand_at(setup: &HandSetup, cost: TableCost) -> HandResult {
|
|
play_hand_tracked(setup, cost, None)
|
|
}
|
|
|
|
/// Like `play_hand_at`, but when a `memory` is given the finished hand's opponent actions are folded
|
|
/// into it (Stage 1 session memory). The read for THIS hand is already fixed in `setup.read`.
|
|
pub fn play_hand_tracked(setup: &HandSetup, cost: TableCost, memory: Option<&mut SessionMemory>) -> HandResult {
|
|
let mut t = Table::new(setup, cost, None);
|
|
t.run();
|
|
if let Some(m) = memory {
|
|
m.observe_hand(&t.history, t.hero, t.players());
|
|
}
|
|
t.result
|
|
}
|
|
|
|
/// Diagnostics: plays one hand and returns hero's result together with a `Dec` for every hero
|
|
/// decision. For localizing where a read helps or hurts (`tests/sim_blind` leak diagnosis); the
|
|
/// benchmark never uses this path.
|
|
pub fn play_hand_traced(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec<Dec>) {
|
|
let mut t = Table::new(setup, cost, Some(Vec::new()));
|
|
t.run();
|
|
(t.result, t.trace.unwrap_or_default())
|
|
}
|