Files
pokerfreak/src/sim/table.rs
T
mmintelandClaude Opus 5.5 4fa0875765 Benchmark harness and mark detection: paired simulation, reader, benchmark binary
Secures work in progress so the rake branch and the shell repo can be merged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 10:36:11 +01:00

366 lines
13 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`. No rake, no antes.
use super::luck;
use super::opponent::{Act, Opponent, View};
use super::reader::{strength, Reading};
use crate::card::{deck, Card};
use crate::engine::decide::decide;
use crate::game::{ActionKind, ActionRecord, Choice, SeenAction, Spot, Street, Villain};
use crate::guard::validate::check;
use crate::hand::showdown::best;
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;
/// 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)
}
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,
}
#[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; must be 0.
pub chips_lost: f64,
/// What the board cards decided (see `sim::luck`); expectation 0.
pub luck: f64,
}
struct Table<'a> {
setup: &'a HandSetup<'a>,
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,
}
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;
}
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);
}
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: None })
.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) => decide(&spot).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.
fn showdown(&self) -> Vec<f64> {
let n = self.players();
let mut won = vec![0.0; n];
let mut left = self.total.clone();
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();
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");
let winners: Vec<usize> = contenders.into_iter().filter(|i| strength[*i] == Some(top)).collect();
for w in &winners {
won[*w] += pot / winners.len() as f64;
}
}
won
}
}
/// Plays one hand to the end and reports hero's result.
pub fn play_hand(setup: &HandSetup) -> HandResult {
let n = setup.deal.holes.len();
let mut t = Table {
setup,
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, luck: 0.0 },
};
let (sb, bb) = if n == 2 { (0, 1) } else { (1, 2) };
t.post(sb, SMALL_BLIND, SeenAction::PostSmallBlind);
t.post(bb, BIG_BLIND, SeenAction::PostBigBlind);
t.round((bb + 1) % n);
for street in [Street::Flop, Street::Turn, Street::River] {
if t.live() < 2 {
break;
}
t.luck_of(street);
t.next_street(street);
t.round(1 % n);
}
let won = t.showdown();
let nets: Vec<f64> = (0..n).map(|i| t.stack[i] + won[i] - setup.stack_bb).collect();
t.result.hero_net = nets[t.hero];
t.result.chips_lost = nets.iter().sum();
t.result
}