//! 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::{Move, Pos, Reveal, SessionMemory, Texture, WorldEvent, WorldHand}; use super::welt; use super::opponent::{Act, Opponent, View}; use super::gto; use super::reader::{strength, Reading}; use crate::card::{deck, Card}; use crate::engine::decide::decide_with; use crate::exploit::profile::Profile; use crate::icm::lage::Turnierlage; use crate::game::{line, 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, } 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) }; /// The live micro table NL 0.01/0.02: no ante, 5 % to the half big blind, cap 10 bb, preflop pots /// raked too (`RakeRule::MICRO_BB`). pub const MICRO: TableCost = TableCost { ante_bb: 0.0, rake: Some(RakeRule::MICRO_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], } thread_local! { static HERO_GTO: std::cell::Cell = const { std::cell::Cell::new(false) }; static HERO_WHY: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; static HERO_READ_DIFF: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// Diagnostics only (`diag_welt DIAG_READ=1`): while on, every engine decision of hero is also taken /// blind (villains without profile, same spot and seed) and counted per node (`node_tag`): /// `[decisions, other action, same action other size]`. Off (default): nothing is computed. pub fn set_hero_read_diff(on: bool) { HERO_READ_DIFF.with(|c| *c.borrow_mut() = on.then(std::collections::BTreeMap::new)); } pub fn take_hero_read_diff() -> std::collections::BTreeMap { HERO_READ_DIFF.with(|c| c.borrow_mut().as_mut().map(std::mem::take).unwrap_or_default()) } /// The node of a decision: street and what hero faces there (`frei` nothing to call, `vs-bet` one /// aggression on the street, `vs-raise` two or more); preflop `vs-bet` is the blinds only. pub fn node_tag(spot: &Spot) -> String { let aggr = spot.history.iter().filter(|r| r.street == spot.street && r.action.is_aggressive()).count(); let facing = if spot.to_call <= 0.0 { "frei" } else if spot.street == Street::Preflop { ["vs-blind", "vs-open", "vs-3bet"][aggr.min(2)] } else if aggr <= 1 { "vs-bet" } else { "vs-raise" }; format!("{:?} {facing}", spot.street) } /// Diagnostics only (`diag_welt`): while on, every engine decision of hero appends /// `" pot/call -> choice | reason"` here; `take_hero_why` returns and clears them. Off (default): /// nothing is recorded and the table is unchanged. pub fn set_hero_why(on: bool) { HERO_WHY.with(|c| *c.borrow_mut() = on.then(Vec::new)); } pub fn take_hero_why() -> Vec { HERO_WHY.with(|c| c.borrow_mut().as_mut().map(std::mem::take).unwrap_or_default()) } /// Measurement only (`ab_zelle`, env `HERO=gto`; thread-local like the other arm switches): hero's seat /// is played by the balanced bot (`sim::gto`, `Shape::BALANCED`) instead of the engine, on the same /// deals, so `engine − bot` per deal is the value of the engine's exploitation. The bot draws from its /// own seed, the table's opponent stream is not touched. Off: the table is unchanged. pub fn set_hero_gto(on: bool) { HERO_GTO.with(|c| c.set(on)); } fn hero_gto() -> bool { HERO_GTO.with(|c| c.get()) } 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), } 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, Debug)] pub struct Dec { pub street: Street, pub pot: f64, pub to_call: f64, pub choice: Choice, pub equity: Option, /// The full spot and the engine's reason (diagnostics: node, hand class, decider). pub spot: Spot, pub reason: String, } #[path = "lbr6.rs"] pub mod lbr6; struct Table<'a> { setup: &'a HandSetup<'a>, cost: TableCost, /// The tournament situation the engine is queried under (`decide_with`). `None` = cash /// (`decide_with(spot, None)` is bit-identical to `decide(spot)`), so the whole cash/exploit /// ladder is untouched; `Some` routes hero through the ICM line (`icm::risk` premium / jam). lage: Option<&'a Turnierlage>, hero: usize, stack: Vec, /// Per-seat starting stacks (big blinds), the baseline for each seat's net. Symmetric /// (`vec![stack_bb; n]`) on the cash/exploit path; the ICM ladder seats asymmetric stacks /// (covering vs covered) through `play_hand_seated`. start: Vec, bet: Vec, total: Vec, folded: Vec, street: Street, max_bet: f64, last_raise: f64, history: Vec, rng: Rng, result: HandResult, /// `Some` only for `play_hand_traced`: one `Dec` per hero decision. trace: Option>, /// Postflop events of a world opponent (`Opponent::Welt`); stays empty for every other opponent. world: Vec, /// The pace of the world opponent's action in progress. welt_tank: Option, /// The opponent on each seat (hero's entry unused). `vec![setup.opponent; n]` everywhere except /// the mixed table (`play_hand_mixed`, the 6-max ladder `sim::sechsmax`). opps: Vec, /// Per-seat reads (hero's entry unused); `Some` only on the mixed table, where it overrides /// `setup.read` seat by seat. seat_reads: Option>>, /// Street and reason text of hero's last decision; kept only on the mixed table. last: Option<(Street, String)>, keep_last: bool, /// The multiway LBR's state (`lbr6`); `None` on every other table. br: Option>, /// Every seat's result after `run` (big blinds). nets: Vec, /// Postflop with more than two players live, a reading opponent's strength is its equity /// against the whole field (`reader::strength_field`), not against one random hand. Only the /// mixed table sets it; heads-up it changes nothing. field_strength: bool, } 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 = (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 = 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) { 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 if self.seat_reads.is_none() => super::reads::opponent_profile(self.setup.opponent), HandRead::Oracle => None, HandRead::Given(p) => p, }; let villains = (0..self.players()) .filter(|j| *j != i) .map(|j| { let profile = self.seat_reads.as_ref().map_or(read, |r| r[j]); Villain { seat: j as u8 + 1, stack: self.stack[j], folded: self.folded[j], profile } }) .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_with(&spot, self.lage); HERO_READ_DIFF.with(|c| { if let Some(m) = c.borrow_mut().as_mut() { let mut blind = spot.clone(); blind.villains.iter_mut().for_each(|v| v.profile = None); let b = decide_with(&blind, self.lage).choice; let e = m.entry(node_tag(&spot)).or_default(); e[0] += 1; if std::mem::discriminant(&b) != std::mem::discriminant(&decision.choice) { e[1] += 1; } else if b != decision.choice { e[2] += 1; } } }); HERO_WHY.with(|c| { if let Some(v) = c.borrow_mut().as_mut() { v.push(format!( "{} pot {:.1} call {:.1} eq {} -> {:?} | {}", node_tag(&spot), spot.pot, spot.to_call, decision.equity.map(|e| format!("{e:.2}")).unwrap_or("-".into()), decision.choice, decision.reason )); } }); 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, spot: spot.clone(), reason: decision.reason.clone(), }); } if self.keep_last { self.last = Some((spot.street, decision.reason)); } decision.choice } Err(_) => { self.result.invalid += 1; if self.keep_last { self.last = Some((self.street, String::from("invalid"))); } 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. /// The seed of seat `i`'s strength estimate on the current street. fn reading_seed(&self, i: usize) -> u64 { self.setup.seed ^ ((i as u64 + 1) << 32) ^ (self.street.board_len() as u64 + 1).wrapping_mul(0x51_7CC1) } fn reading(&self, i: usize) -> Reading { let board = &self.setup.deal.board[..self.street.board_len()]; let seed = self.reading_seed(i); let hole = &self.setup.deal.holes[i]; let live = self.live(); let strength = if self.field_strength && self.street != Street::Preflop && live > 2 { super::reader::strength_field(hole, board, live - 1, Rng::seeded(seed)) } else { strength(hole, board, Rng::seeded(seed)) }; Reading { strength, pot: self.total.iter().sum(), own_bet: self.bet[i], preflop: self.street == Street::Preflop, } } /// Acts last among the live players after the flop (the table's seat order after the button). fn in_position(&self, i: usize) -> bool { let n = self.players(); let key = |j: usize| (j + n - 1) % n; (0..n).all(|j| j == i || self.folded[j] || key(j) < key(i)) } /// One action of seat `i`. For a world opponent (`Opponent::Welt`) the postflop action is also /// logged as a `WorldEvent` (what an observer sees: street, texture, position, move, size, pace). fn act(&mut self, i: usize) -> bool { let welt = matches!(self.opps[i], Opponent::Welt(_)) && i != self.hero && self.street != Street::Preflop; if !welt { return self.act_inner(i); } let (len, pot, bet, to_call) = (self.history.len(), self.total.iter().sum::(), self.bet[i], self.view(i).to_call); let (texture, pos) = (Texture::of(&self.setup.deal.board[..self.street.board_len()]), if self.in_position(i) { Pos::Ip } else { Pos::Oop }); self.welt_tank = None; let raised = self.act_inner(i); if let Some(r) = self.history.get(len).copied() { let amount = r.amount.unwrap_or(0.0); let aggressive = r.action.is_aggressive() && amount > bet + to_call + EPS; let mv = match r.action { SeenAction::Fold => Move::Fold, _ if aggressive && to_call > EPS => Move::Raise, _ if aggressive => Move::Bet, _ if to_call > EPS => Move::Call, _ => Move::Check, }; let size_frac = aggressive.then(|| (amount - bet - to_call) / (pot + to_call)); self.world.push(WorldEvent { seat: r.seat, street: self.street, texture, pos, mv, size_frac, tank: self.welt_tank }); } raised } /// The finished hand's world observations: the logged events, and every hand still live at the /// showdown revealed (`None` when the hand ended before one). /// The opponents' river bets shown at this hand's showdown into `m` (`RIVER_SD=1`, see /// `SessionMemory::observe_river_reveal`). fn river_reveals(&self, m: &mut SessionMemory) { if self.live() < 2 { return; } for i in (0..self.players()).filter(|i| *i != self.hero && !self.folded[*i]) { let seat = i as u8 + 1; let bets = self.history.iter().filter(|r| r.street == Street::River && r.seat == seat && r.action.is_aggressive()).count(); m.observe_river_reveal(&self.setup.deal.holes[i], &self.setup.deal.board, bets as u32); } } fn world_hand(&self) -> WorldHand { let mut hand = WorldHand { events: self.world.clone(), reveals: Vec::new() }; if self.live() >= 2 { for i in (0..self.players()).filter(|i| *i != self.hero && !self.folded[*i]) { hand.reveals.push(Reveal { seat: i as u8 + 1, hole: self.setup.deal.holes[i], board: self.setup.deal.board.to_vec() }); } } hand } /// The balanced bot (`sim::gto`) on seat `i`: the gto opponent, and hero under `set_hero_gto`. fn gto_act(&self, i: usize, view: View, shape: gto::Shape, rng: Rng) -> (Act, Rng) { let reading = self.reading(i); let n = self.players(); let key = |j: usize| (j + n - 1) % n; let in_position = (0..n).all(|j| j == i || self.folded[j] || key(j) < key(i)); let seed = self.setup.seed ^ ((i as u64 + 1) << 40) ^ (self.history.len() as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (self.street.board_len() as u64 + 1).wrapping_mul(0xC2B2_AE3D_27D4_EB4F); let ctx = gto::Ctx { hole: &self.setup.deal.holes[i], board: &self.setup.deal.board[..self.street.board_len()], strength: reading.strength, pot: reading.pot, own_bet: reading.own_bet, stack: self.stack[i], seat: i, players: n, live: self.live(), in_position, history: &self.history, seed, shape, }; gto::act(view, &ctx, rng) } fn act_inner(&mut self, i: usize) -> bool { let view = self.view(i); // Multiway LBR (`lbr6`): the best-responder's seat plays its own policy; before any other // seat acts, the state is kept so its particles can be weighed by what it actually does. if self.br.as_ref().is_some_and(|b| b.seat == i) { let act = lbr6::decide(self, i, view); return self.apply(i, view, act); } let before = self.br.is_some().then(|| self.snapshot()); let act = self.choose(i, view); if let Some(before) = before { lbr6::observe(self, &before, i, view, act); } self.apply(i, view, act) } /// What seat `i` (hero or a fixed opponent) plays facing `view`; advances the table's rng. fn choose(&mut self, i: usize, view: View) -> Act { if i == self.hero && hero_gto() { self.result.hero_decisions += 1; let rng = Rng::seeded(self.setup.seed ^ 0x6E70_4845_524F ^ (self.history.len() as u64 + 1).wrapping_mul(0x9E37_79B9)); self.gto_act(i, view, gto::Shape::BALANCED, rng).0 } else if i == self.hero { self.hero_act(view) } else { let (act, rng) = match self.opps[i] { Opponent::Welt(p) => { let reading = self.reading(i); let ctx = welt::Ctx { reading, street: self.street, texture: Texture::of(&self.setup.deal.board[..self.street.board_len()]), pos: if self.in_position(i) { Pos::Ip } else { Pos::Oop }, facing_cbet: line::facing_cbet(&self.history, i as u8 + 1), facing_three_bet: line::facing_three_bet(&self.history, i as u8 + 1), checked_here: line::check_raise_chance(&self.history, i as u8 + 1, self.street), }; let (act, rng) = welt::act(&p, view, &ctx, self.rng); let (tank, rng) = p.tank_factor(reading.strength, rng); self.welt_tank = Some(tank); (act, rng) } Opponent::Reader(style) if style.gto_shape().is_some() => { self.gto_act(i, view, style.gto_shape().expect("gto-family style has a shape"), self.rng) } Opponent::Reader(style) => style.act(view, self.reading(i), self.rng), Opponent::Styled(rules) => super::reader::act_with(rules, view, self.reading(i), self.rng), Opponent::Lerner(z) => super::lerner::act(&z, view, self.reading(i), self.street, self.rng), blind => blind.act(view, self.rng), }; self.rng = rng; let act = self.vorflop_tor(i, view, act); let act = self.bettor_tor(i, view, act); let act = self.river_call(i, view, act); self.pool_ruf(i, view, act) } } /// Das geeichte Vorflop-Spiel (`sim::vorflop_tor`, `SIM_VORFLOP`): heads-up spielt ein Pool-Gegner vorflop nach /// gemessenen Frequenzen echter Spieler statt nach seinen Nach-Flop-Schwellen. Aus (Standard) gibt es `act` /// unverändert zurück; der Tisch-Rng wird nie berührt. fn vorflop_tor(&self, i: usize, view: View, act: Act) -> Act { use super::vorflop_tor::Spot as V; if self.street != Street::Preflop || i == self.hero || self.setup.deal.holes.len() != 2 || !super::vorflop_tor::enabled() { return act; } match self.opps[i] { Opponent::Welt(p) if super::bettor_tor::gilt(p.label) => {} _ => return act, } let seat = i as u8 + 1; let sb = self.history.iter().any(|r| r.seat == seat && r.action == SeenAction::PostSmallBlind); let vol: Vec<&ActionRecord> = self .history .iter() .filter(|r| r.street == Street::Preflop && !matches!(r.action, SeenAction::PostSmallBlind | SeenAction::PostBigBlind | SeenAction::PostAnte)) .collect(); let raises = vol.iter().filter(|r| r.action.is_aggressive()).count(); let own: Vec = vol.iter().filter(|r| r.seat == seat).map(|r| r.action).collect(); let spot = match (sb, own.as_slice(), raises, vol.len()) { (true, [], 0, 0) => V::Sb, (false, [], 0, 1) if vol[0].action == SeenAction::Call => V::BbLimp, (true, [SeenAction::Call], 1, 2) => V::SbLimpR, (false, [], 1, 1) => V::BbOpen, (true, [a], 2, 2) if a.is_aggressive() => V::Sb3b, (false, [a], 3, 3) if a.is_aggressive() => V::Bb4b, _ => return act, }; let pct = crate::preflop::hand_percentile::percentile(crate::variant::Variant::Nlhe, &self.setup.deal.holes[i]); super::vorflop_tor::answer(spot, pct).and_then(|a| super::vorflop_tor::act_of(a, spot, view)).unwrap_or(act) } /// Das geeichte Setzverhalten (`sim::bettor_tor`, `SIM_BETTOR`): an der offenen Entscheidung einer /// Nach-Flop-Straße heads-up ersetzt es Check/Einsatz eines Pool-Gegners durch eine Ziehung aus der /// gemessenen Tabelle. Aus (Standard) gibt es `act` unverändert zurück; der Tisch-Rng wird nie berührt. fn bettor_tor(&self, i: usize, view: View, act: Act) -> Act { if self.street == Street::Preflop || view.to_call > EPS || i == self.hero || self.live() != 2 || self.folded[self.hero] { return act; } if !super::bettor_tor::enabled() { return act; } match self.opps[i] { Opponent::Welt(p) if super::bettor_tor::gilt(p.label) => {} _ => return act, } let seat = i as u8 + 1; if self.history.iter().any(|r| r.street == self.street && r.action.is_aggressive()) { return act; } let pfa = self.history.iter().rev().find(|r| r.street == Street::Preflop && r.action.is_aggressive()).is_some_and(|r| r.seat == seat); let before = self.street != Street::Flop && self.history.iter().any(|r| r.seat == seat && r.street as usize + 1 == self.street as usize && r.action.is_aggressive()); let board = &self.setup.deal.board[..self.street.board_len()]; let p = super::bettor_tor::percentile(&self.setup.deal.holes[i], board); let salz = self.setup.seed ^ 0x4245_5454_4f52 ^ ((self.street as u64 + 1) << 40) ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); let (u, rng) = Rng::seeded(salz).unit(); let (v, _) = rng.unit(); let Some(a) = super::bettor_tor::answer((self.street, pfa, before), p, u) else { return act }; let pot: f64 = self.total.iter().sum(); super::bettor_tor::act_of(a, v, pot, view).unwrap_or(act) } /// Die stärkebewusste NL2-Antwort (`sim::poolruf`): auf den ersten Einsatz einer Nach-Flop-Straße (oder einen /// Raise über den eigenen Einsatz) ersetzt sie Call/Fold eines Pool-Gegners durch die Call-Wahrscheinlichkeit /// seiner Handklasse. Ein Raise bleibt. Aus (Standard) und ohne Mitschrift gibt sie `act` unverändert zurück; /// der Tisch-Rng wird nie berührt. fn pool_ruf(&self, i: usize, view: View, act: Act) -> Act { if self.street == Street::Preflop || view.to_call <= EPS || !super::poolruf::aktiv() { return act; } let gegner = match self.opps[i] { Opponent::Welt(p) => p.label, Opponent::Reader(style) if style.gto_shape().is_none() => style.name(), Opponent::Styled(_) => "styled", Opponent::Lerner(_) => "lerner", _ => return act, }; let strasse = match self.street { Street::Flop => 0, Street::Turn => 1, _ => 2, }; // Die Einsätze dieser Straße: erster Setzer, letzter Erhöher. let mut hoch = 0.0; let mut setzer = Vec::new(); let mut erst_k = 0; for (k, r) in self.history.iter().enumerate().filter(|(_, r)| r.street == self.street) { if let Some(a) = r.amount { if r.action.is_aggressive() && a > hoch + EPS { hoch = a; if setzer.is_empty() { erst_k = k; } setzer.push(r.seat as usize - 1); } } } let (gruppe_fest, wer) = match setzer.as_slice() { [s] if *s != i => (None, *s), [s, r] if *s == i && *r != i => (Some(3), *r), _ => return act, }; let basis = match act { Act::RaiseTo(_) => 'r', Act::Fold => 'f', _ => 'c', }; let topf: f64 = self.total.iter().sum::() - self.bet.iter().sum::(); let r = self.max_bet / topf.max(EPS); let allin = self.stack[wer] <= EPS; let gruppe = gruppe_fest.unwrap_or_else(|| super::poolruf::gruppe(r, allin)); let spaeter_raus = self.history[erst_k..].iter().filter(|x| x.street == self.street && x.action == SeenAction::Fold).count(); let mw = self.live() + spaeter_raus > 2; let brett = &self.setup.deal.board[..self.street.board_len()]; let hole = &self.setup.deal.holes[i]; let klasse = super::poolruf::klasse(hole, brett); let neu = match super::poolruf::p_call(strasse, gruppe, mw, klasse) { Some(p) if basis != 'r' && super::poolruf::gilt(gegner) => { let salz = self.setup.seed ^ 0x504f_4f4c_5255_4600 ^ ((strasse as u64 + 1) << 40) ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); let (u, _) = Rng::seeded(salz).unit(); if u < p { Act::Call } else { Act::Fold } } _ => act, }; super::poolruf::mitschreiben(&super::poolruf::Begegnung { gegner, strasse, gruppe, r, allin, mw, setzer_hero: wer == self.hero, klasse, s: strength(hole, brett, Rng::seeded(self.reading_seed(i))), gegen_setzer: super::poolruf::gegen(hole, &self.setup.deal.holes[wer], &self.setup.deal.board[..5]), basis, tor: match neu { Act::RaiseTo(_) => 'r', Act::Fold => 'f', _ => 'c', }, setzer_klasse: super::poolruf::klasse(&self.setup.deal.holes[wer], brett), einsatz: self.max_bet, }); neu } /// Die geeichte River-Call-Antwort (`sim::rivercall`): auf den ersten River-Einsatz eines anderen Spielers /// ersetzt sie Call/Fold eines lesenden Gegners durch die PHH-Schwelle seiner Stilklasse. Ein Raise bleibt. /// Aus (Standard) und ohne Mitschrift gibt sie `act` unverändert zurück; der Tisch-Rng wird nie berührt. fn river_call(&self, i: usize, view: View, act: Act) -> Act { if self.street != Street::River || view.to_call <= EPS || !super::rivercall::aktiv() { return act; } let (rules, gegner) = match self.opps[i] { Opponent::Welt(p) => (p.rules, p.label), Opponent::Reader(style) if style.gto_shape().is_none() => (style.rules(), style.name()), Opponent::Styled(r) => (r, "styled"), Opponent::Lerner(z) => (z.rules, "lerner"), _ => return act, }; // Genau ein Einsatz am River bisher (der erste), nicht vom Antwortenden selbst. let river: Vec<(usize, &ActionRecord)> = self.history.iter().enumerate().filter(|(_, r)| r.street == Street::River).collect(); let mut hoch = 0.0; let mut einsatz = None; let mut erhoehungen = 0; for (k, r) in &river { if let Some(a) = r.amount { if r.action.is_aggressive() && a > hoch + EPS { erhoehungen += 1; hoch = a; einsatz = Some((*k, r.seat as usize - 1)); } } } let Some((k, setzer)) = einsatz else { return act }; if erhoehungen != 1 || setzer == i { return act; } let basis = match act { Act::RaiseTo(_) => 'r', Act::Fold => 'f', _ => 'c', }; let topf: f64 = self.total.iter().sum::() - self.bet.iter().sum::(); let spaeter_raus = self.history[k..].iter().filter(|r| r.street == Street::River && r.action == SeenAction::Fold).count(); let lage = super::rivercall::Lage { r: self.max_bet / topf.max(EPS), allin: self.stack[setzer] <= EPS, mw: self.live() + spaeter_raus > 2, }; let klasse = super::rivercall::Klasse::von(&rules); let board = &self.setup.deal.board[..5]; let hole = &self.setup.deal.holes[i]; let s = strength(hole, board, Rng::seeded(self.reading_seed(i))); let neu = if basis == 'r' || !super::rivercall::enabled() { act } else { let (u, _) = Rng::seeded(self.setup.seed ^ 0x5249_5645_5243 ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15)).unit(); if super::rivercall::ruft(klasse, &lage, s, u) { Act::Call } else { Act::Fold } }; super::rivercall::mitschreiben(&super::rivercall::Begegnung { gegner, klasse, lage, setzer_hero: setzer == self.hero, s, vs2p: super::rivercall::vs_2p(hole, board), gegen_setzer: super::rivercall::gegen(hole, &self.setup.deal.holes[setzer], board), basis, tor: match neu { Act::RaiseTo(_) => 'r', Act::Fold => 'f', _ => 'c', }, }); neu } /// Carries out `act` of seat `i`; true when it raised. fn apply(&mut self, i: usize, view: View, act: Act) -> bool { 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 = (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) { 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)> = Vec::new(); loop { let contenders: Vec = (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 = 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>, lage: Option<&'a Turnierlage>, start: Option>, ) -> Table<'a> { let n = setup.deal.holes.len(); let start = start.unwrap_or_else(|| vec![setup.stack_bb; n]); Table { setup, cost, lage, hero: setup.hero_seat as usize - 1, stack: start.clone(), start, 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, world: Vec::new(), welt_tank: None, opps: vec![setup.opponent; n], seat_reads: None, last: None, keep_last: false, br: None, nets: Vec::new(), field_strength: false, } } /// A copy of the state for a what-if query (`lbr6`): no trace, no LBR state. fn snapshot(&self) -> Table<'a> { self.with_setup(self.setup) } /// The same state at a table whose deal differs (another hole for one seat): the copy plays /// the seat's policy on those cards with the SAME randomness the table had at this point. fn with_setup<'b>(&self, setup: &'b HandSetup<'b>) -> Table<'b> where 'a: 'b, { Table { setup, cost: self.cost, lage: self.lage, hero: self.hero, stack: self.stack.clone(), start: self.start.clone(), bet: self.bet.clone(), total: self.total.clone(), folded: self.folded.clone(), street: self.street, max_bet: self.max_bet, last_raise: self.last_raise, history: self.history.clone(), rng: self.rng, result: self.result, trace: None, world: Vec::new(), welt_tank: None, opps: self.opps.clone(), seat_reads: self.seat_reads.clone(), last: None, keep_last: false, br: None, nets: Vec::new(), field_strength: self.field_strength, } } /// 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 = (0..n).map(|i| self.stack[i] + won[i] - self.start[i]).collect(); self.result.hero_net = nets[self.hero]; self.result.rake = rake; self.result.chips_lost = nets.iter().sum::() + rake; self.nets = nets; } } /// 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, None, None); t.run(); if let Some(m) = memory { m.observe_hand(&t.history, t.hero, t.players()); if matches!(setup.opponent, Opponent::Welt(_)) { m.observe_world_hand(&t.world_hand()); } else { t.river_reveals(m); } } t.result } /// `play_hand_tracked` with the hero trace (diagnostics: the same hand, the same memory update). pub fn play_hand_tracked_traced(setup: &HandSetup, cost: TableCost, memory: Option<&mut SessionMemory>) -> (HandResult, Vec) { let mut t = Table::new(setup, cost, Some(Vec::new()), None, None); t.run(); if let Some(m) = memory { m.observe_hand(&t.history, t.hero, t.players()); if matches!(setup.opponent, Opponent::Welt(_)) { m.observe_world_hand(&t.world_hand()); } else { t.river_reveals(m); } } (t.result, t.trace.unwrap_or_default()) } /// Plays one hand at the free table with explicit per-seat starting stacks and hero on the line /// `lage` selects: `Some` queries the engine `decide_with(spot, Some(lage))` (the ICM line — risk /// premium / open-jam widening), `None` the cash chip-EV line at the SAME stacks (a fair paired /// control). `start[seat]` is the seat's stack in big blinds; its length must match the deal. /// `lage.stacks` is the field in the same unit (hero at `lage.hero`, the table opponent next); the /// chips move only at the table, the `Turnierlage` prices them. The strength ladder /// (`sim::turnier_leiter`) pairs the two lines on identical deals and stacks and scores the chip /// outcome back into ICM money. pub fn play_hand_seated(setup: &HandSetup, start: &[f64], lage: Option<&Turnierlage>) -> HandResult { let mut t = Table::new(setup, TableCost::FREE, None, lage, Some(start.to_vec())); t.run(); 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) { let mut t = Table::new(setup, cost, Some(Vec::new()), None, None); t.run(); (t.result, t.trace.unwrap_or_default()) } /// Diagnostics (`diag_welt`): `play_hand_tracked` that also returns the full action history. pub fn play_hand_tracked_history( setup: &HandSetup, cost: TableCost, memory: Option<&mut SessionMemory>, ) -> (HandResult, Vec) { let mut t = Table::new(setup, cost, None, None, None); t.run(); if let Some(m) = memory { m.observe_hand(&t.history, t.hero, t.players()); if matches!(setup.opponent, Opponent::Welt(_)) { m.observe_world_hand(&t.world_hand()); } else { t.river_reveals(m); } } (t.result, t.history) } /// Plays one hand and returns hero's result together with the full action history, so a caller can /// update BOTH a hero-side read and an opponent-side model of the hero (`sim::adaptive`, Stufe 3). pub fn play_hand_history(setup: &HandSetup, cost: TableCost) -> (HandResult, Vec) { let mut t = Table::new(setup, cost, None, None, None); t.run(); (t.result, t.history) } /// One hand at a MIXED table: `opponents[seat - 1]` plays each seat (hero's entry is ignored) and /// `reads[seat - 1]` is the profile the engine sees on that seat (`setup.opponent` and `setup.read` /// are then unused). Returns hero's result, the action history (for per-opponent memories) and the /// street and reason text of hero's LAST decision (`start`: per-seat stacks, `None` = all `stack_bb`) (`None`: hero never had to act, e.g. a walk in the /// big blind). The 6-max ladder (`sim::sechsmax`) and the multiway LBR are built on it. Reading /// opponents judge their hand against the whole field postflop (`reader::strength_field`). pub fn play_hand_mixed( setup: &HandSetup, cost: TableCost, opponents: &[Opponent], reads: &[Option], start: Option<&[f64]>, ) -> (HandResult, Vec, Option<(Street, String)>) { assert_eq!(opponents.len(), setup.deal.holes.len(), "one opponent per seat"); assert_eq!(reads.len(), setup.deal.holes.len(), "one read per seat"); let mut t = Table::new(setup, cost, None, None, start.map(<[f64]>::to_vec)); t.opps = opponents.to_vec(); t.seat_reads = Some(reads.to_vec()); t.keep_last = true; t.field_strength = true; t.run(); (t.result, t.history, t.last) }