From 79cb24e2795cf7f587f27c484c277612e66249be Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Sat, 14 Nov 2026 22:09:20 +0100 Subject: [PATCH] =?UTF-8?q?Turnier=20live:=20Erkennung=20aus=20dem=20Log,?= =?UTF-8?q?=20ICM-Push/Fold-Solver,=20Chip-EV-R=C3=BCckfall=20in=20decide.?= =?UTF-8?q?py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lesen/spot_from_log: Turnierlage aus Beitrittszeile ODER Tisch-Rahmen (tournamentlobby.*); fehlt etwas, spielt der Tisch Chip-EV mit Grund in _turnier - entscheiden/decide.py: Modus in Antwort/Begründung; unbepreisbare Lage -> einmal als Chip-EV - src/icm/push_fold.rs: ICM-Nash Push/Fold (<=15bb first-in, Call gegen lone Jam <=25bb), fiktives Spiel über 169 Klassen, Antes im Pot; exploit_border ohne ICM-Doppelzählung - turnier_leiter ab: gepaarter A/B Solver vs kalibriert - tests/turnier_spots_spec: 8 Spots + Rückfall; Cash unberührt Co-Authored-By: Claude Opus 5.5 --- entscheiden/decide.py | 29 ++ lesen/spot_from_log.py | 54 +++- src/bin/turnier_leiter.rs | 16 +- src/engine/decide.rs | 49 ++- src/icm/mod.rs | 1 + src/icm/push_fold.rs | 505 +++++++++++++++++++++++++++++ src/preflop/advise.rs | 2 +- src/sim/turnier_leiter.rs | 55 ++++ tests/turnier_anfrage_spec.py | 579 ++++++++++++++++++---------------- tests/turnier_spots.py | 71 +++++ tests/turnier_spots_spec.py | 106 +++++++ 11 files changed, 1179 insertions(+), 288 deletions(-) create mode 100644 src/icm/push_fold.rs create mode 100644 tests/turnier_spots.py create mode 100644 tests/turnier_spots_spec.py diff --git a/entscheiden/decide.py b/entscheiden/decide.py index 2f4db2b7..50dcf0e8 100644 --- a/entscheiden/decide.py +++ b/entscheiden/decide.py @@ -100,6 +100,35 @@ def entscheide(anfragen, timeout=30): antworten.append(json.loads(zeile)) except Exception: antworten.append({"action": "ABSTAIN", "reason": "Antwort unlesbar"}) + return _turnier(anfragen, antworten, timeout) + + +def _turnier(anfragen, antworten, timeout): + """Turniertische (Anfrage mit `_turnier` aus lesen/spot_from_log): der Modus geht in die Antwort + (`turnier`: "ICM" oder "Chip-EV-Rückfall: ") und an die Begruendung - so steht im Log, WARUM + ein Turniertisch Chip-EV spielt. Kann der Kern eine Turnierlage nicht bepreisen (ABSTAIN + "tournament situation ..."), wird dieselbe Anfrage einmal OHNE `tournament` als Chip-EV gestellt: + am echten Tisch hiesse Aussetzen blind folden/checken. Cash-Anfragen (ohne `_turnier`/`tournament`) + bleiben unberuehrt.""" + nochmal = {} + for i, (zeile, a) in enumerate(zip(anfragen, antworten)): + try: + frage = json.loads(zeile) + except ValueError: + continue + if not isinstance(frage, dict) or not isinstance(a, dict): + continue + if ("tournament" in frage and a.get("action") == "ABSTAIN" + and "tournament situation" in str(a.get("reason", ""))): + ohne = {k: v for k, v in frage.items() if k != "tournament"} + ohne["_turnier"] = f"Chip-EV-Rückfall: Kern: {a.get('reason')}" + nochmal[i] = json.dumps(ohne) # ASCII: unter Windows geht stdin sonst als cp1252 + elif frage.get("_turnier"): + a["turnier"] = frage["_turnier"] + a["reason"] = f"{a.get('reason', '')} | Turnier: {frage['_turnier']}" + if nochmal: + for i, b in zip(list(nochmal), entscheide(list(nochmal.values()), timeout)): + antworten[i] = b return antworten diff --git a/lesen/spot_from_log.py b/lesen/spot_from_log.py index 4a0693b7..c0c2c8dc 100644 --- a/lesen/spot_from_log.py +++ b/lesen/spot_from_log.py @@ -117,7 +117,13 @@ Turnier (Spezifikation: tests/turnier_anfrage_spec.py, Lage: lesen/turnier.py): `Comm_Tournament_`). ANNAHME: im Bestand ist kein Turniertisch aufgenommen (tournamentId überall 0); die Lobby-Meldungen selbst (`receive_from_tournament_lobby`) sind. * Am Turniertisch trägt die Anfrage `tournament` {payouts, stacks, heroIndex, ante, level} aus dem Stand der - Lobby VOR dem Zug (turnier.kern_feld). Fehlen Preise, Rangliste oder Level: aussetzen ("Turnier:..."). + Lobby VOR dem Zug (turnier.kern_feld). Quellen der Lobby: der Lobby-Kanal (`receive_from_tournament_lobby`, + Raum `Comm_Tournament_`) UND der Tischkanal (`cmd_bean.Cmd` = `tournamentlobby.*` am Tischraum, gemessen + 04.11., lesen/turnier.tisch_frame); je Art zählt die jüngste Meldung vor dem Zug. Ein Tisch mit solchen + Rahmen ist ein Turniertisch, auch ohne Beitrittszeile. + * Fehlt etwas (Lobby unbekannt, Preise, Rangliste, Level, eigener Stapel): KEIN Aussetzen - der Tisch spielt + sicher Chip-EV (ohne `tournament`), und `_turnier` nennt den Grund ("Chip-EV-Rückfall: Turnier: ..."). + Aussetzen hiesse am echten Tisch: der Laeufer foldet/checkt blind (Owner 9.11.). Mit Lage: `_turnier` "ICM". from spot_from_log import spots """ @@ -153,6 +159,8 @@ BEAN = re.compile( r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[A-Za-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"') # Beitritt: lobby.join_game_table (Tischname + roomProperties) und die Anfrage davor BEAN_BEITRITT = re.compile(BEAN.pattern.replace(r"(game\.[A-Za-z_]+)", r"(lobby\.join_game_table)")) +# Turnier-Lobby auf dem TISCHkanal (gemessen 04.11.): cmd_bean.Cmd = tournamentlobby., RoomName = Tisch +BEAN_TURNIER = re.compile(BEAN.pattern.replace(r"(game\.[A-Za-z_]+)", r"(tournamentlobby\.[a-z_]+)")) BEITRITT = re.compile(r"SendExtensionMessageToConnector - lobby\.join_game - (\{[^\r\n]*\})") BLINDS = re.compile(r"NL ([\d.]+)-([\d.]+)") STREETS = ("FLOP", "TURN", "RIVER") @@ -303,6 +311,7 @@ class Tisch: self.rit = False # roomProperties.isRit - der Tisch bietet RIT an self.raum_rp = {} # roomProperties aus game_alldata, siehe `format` self.lobby = None # Turniertisch: Raum der Turnierlobby (Comm_Tournament_), siehe `merke_turnier` + self.lobby_tisch = {} # Lobby-Rahmen vom Tischkanal: {art: (Stelle, Daten)} (turnier.tisch_frame) def merke_turnier(self, d): """`tourneyTableProperties` aus game_alldata: `tourneyLobbyName`, sonst @@ -474,8 +483,14 @@ class Tisch: and r["street"] == strasse and r["action"] != "POST_ANTE"), default=0) return self.chips[sitz] + drin + def turniertisch(self): + """Ein Turniertisch: Lobby bekannt, Lobby-Rahmen am Tisch, oder gameType "Tournament".""" + return bool(self.lobby or self.lobby_tisch + or (self.art is not None and self.art.get("gameType") == TURNIER_SPIELART)) + def anfrage(self, turn, lobby=None): - """`lobby`: Stand der Turnierlobby dieses Tisches ({art: letzte Meldung}), am Turniertisch.""" + """`lobby`: Stand der Turnierlobby dieses Tisches ({art: (Stelle, Meldung)}) vom Lobby-Kanal; die + Rahmen vom Tischkanal (`lobby_tisch`) kommen dazu, je Art gilt die juengere.""" hand = turn.get("gameHandId") self.neuer_hand(hand) treffer = BLINDS.search(self.room) @@ -523,10 +538,20 @@ class Tisch: if bb is None: unklar, bb = unklar or "Big Blind unbekannt", 0.0 held_seat = held[0] if held else None - feld = None - if self.lobby and held_seat is not None: - feld, grund = turnier.kern_feld(lobby, self.ich, self.start_stapel(held_seat)) - unklar = unklar or grund + feld, turnier_grund = None, None + if self.turniertisch() and held_seat is not None: + stand = dict(lobby or {}) + for art, (stelle, d) in self.lobby_tisch.items(): + if art not in stand or stand[art][0] < stelle: + stand[art] = (stelle, d) + if self.lobby or stand: + feld, grund = turnier.kern_feld({a: d for a, (_, d) in stand.items()}, self.ich, + self.start_stapel(held_seat)) + else: + grund = "Turnier: Lobby unbekannt" + # Sicher auf Chip-EV zurueck statt auszusetzen: ohne Lage spielt der Kern den Tisch wie Cash (kein + # Raten von Preisen); der Grund geht mit (`_turnier`) und landet ueber decide.py in der Begruendung. + turnier_grund = "ICM" if feld else f"Chip-EV-Rückfall: {grund}" if unklar: legal = [] if aof and not unklar: @@ -585,7 +610,7 @@ class Tisch: # RIT-Angebot: der Kern antwortet nur darauf; das Fenster prueft danach der Laeufer **({"ritOffered": True} if self.rit else {}), "history": [dict(r, seat=plan[r["seat"]]) for r in self.verlauf], - "tournament": feld, "evChop": True if self.ev_chop else None, + "tournament": feld, "evChop": True if self.ev_chop else None, "_turnier": turnier_grund, "_unklar": unklar, "_sitze": {neu: alt for alt, neu in plan.items()}, } anfrage = {k: v for k, v in anfrage.items() if v not in (None, {}, [])} @@ -658,6 +683,7 @@ def _ereignisse(text): folge = [(m.start(), "bohne", m) for m in BEAN.finditer(text)] folge += [(m.start(), "beitritt", m) for m in BEAN_BEITRITT.finditer(text)] folge += [(m.start(), "anfrage", m) for m in BEITRITT.finditer(text)] + folge += [(m.start(), "tischlobby", m) for m in BEAN_TURNIER.finditer(text)] return sorted(folge, key=lambda e: e[0]) @@ -703,10 +729,20 @@ def spots(text, beobachter=None, arten=None): beitrittsanfrage = None lobbys = {} # Turnierlobby -> {art: letzte Meldung} (lesen/turnier.py) folge = _ereignisse(text) + [(stelle, "lobby", (raum, art, d)) for stelle, raum, art, d in turnier.meldungen(text)] - for _, art, m in sorted(folge, key=lambda e: e[0]): + for stelle, art, m in sorted(folge, key=lambda e: e[0]): if art == "lobby": raum, was, d = m - lobbys.setdefault(raum, {})[was] = d + lobbys.setdefault(raum, {})[was] = (stelle, d) + continue + if art == "tischlobby": + was = turnier.ARTEN.get(m.group(2)) + try: + d = json.loads(_unescape(m.group(1))) + except Exception: + continue + if was and isinstance(d, dict): + raum = UMBRUCH.sub("", m.group(3)) + tische.setdefault(raum, Tisch(raum)).lobby_tisch[was] = (stelle, d) continue if art == "anfrage": try: diff --git a/src/bin/turnier_leiter.rs b/src/bin/turnier_leiter.rs index 9e092d1a..16d8c4b6 100644 --- a/src/bin/turnier_leiter.rs +++ b/src/bin/turnier_leiter.rs @@ -10,10 +10,12 @@ //! (Eiserne Regel: nie einen Verlierer shippen) — dann zurückrollen und Befund. //! //! Run: `cargo run --release --bin turnier_leiter [deals]` (default 2000). +//! A/B des ICM-Push/Fold-Solvers: `turnier_leiter ab [deals]` - beide Linien im Turnier, A mit dem +//! Solver (`icm::push_fold`), B ohne (kalibrierter Chip-Pfad + ICM-Praemie). Kante = Solver − alt. use rechner::sim::opponent::Opponent; use rechner::sim::reader::Style; -use rechner::sim::turnier_leiter::{messen, Szenario, TurnierMessung}; +use rechner::sim::turnier_leiter::{messen, messen_solver, Szenario, TurnierMessung}; const SEED: u64 = 0x5EED_0001; @@ -88,14 +90,20 @@ fn mark(m: &TurnierMessung) -> &'static str { } fn main() { - let deals: u32 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(2000); + let args: Vec = std::env::args().skip(1).collect(); + let ab = args.first().is_some_and(|a| a == "ab"); + let deals: u32 = args.iter().find_map(|s| s.parse().ok()).unwrap_or(2000); println!("=== Turnier-Stärke-Leiter, {deals} Austeilungen/Szenario (Pool = 100) ==="); - println!("Kante = ICM$(an) - ICM$(aus) je 100 Hände, gepaart, 95-%-Intervall."); + if ab { + println!("A/B Push/Fold-Solver: Kante = ICM$(Solver) - ICM$(kalibriert) je 100 Hände, gepaart."); + } else { + println!("Kante = ICM$(an) - ICM$(aus) je 100 Hände, gepaart, 95-%-Intervall."); + } println!("A=Anker (Ziel ~0) B=Bubble/FT (Ziel >0) J=Jam-Druck\n"); println!(" {:<17} {:>3} {:>9} {:>8} {:>9} {:>9} {}", "szenario", "typ", "kante", "±ci", "an", "aus", "urteil"); let mut leck = false; for (sz, typ) in szenarien(deals) { - let m = messen(&sz); + let m = if ab { messen_solver(&sz) } else { messen(&sz) }; if m.invalid > 0 { println!(" !! {} INVALID {}", sz.name, m.invalid); } diff --git a/src/engine/decide.rs b/src/engine/decide.rs index 64cf3d18..beb50211 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -15,9 +15,14 @@ use crate::exploit::thresholds::Thresholds; use crate::game::{Decision, Spot, Street}; use crate::guard::enforce::enforce; use crate::icm::lage::Turnierlage; +use crate::icm::push_fold::push_fold; use crate::icm::risk::{call_premium, jam_depth_gate, jam_pressure, jam_width_factor, width_factor}; -use crate::preflop::advise::advise_widened; -use crate::preflop::plan::PreflopPlan; +use crate::preflop::advise::{advise_widened, scale_for}; +use crate::preflop::certainty::certainty; +use crate::preflop::exploit_border::exploit_border; +use crate::preflop::hand_percentile::percentile; +use crate::preflop::plan::{ChartAction, PreflopPlan}; +use crate::preflop::situation_of::situation_of; use crate::read::hand_read::read; use crate::rng::Rng; @@ -123,12 +128,44 @@ fn with_premium(thresholds: Thresholds, premium: f64) -> Thresholds { } } -fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot) -> Decision { +/// Tournament short stack (`icm::push_fold`): the jam/call-or-fold answer of the ICM push/fold +/// equilibrium, its border moved only by the EXPLOIT width (`scale_for` on the thresholds WITHOUT the +/// ICM premium - the premium is already inside the prize-money terminals, counting it twice would +/// over-tighten). `None` where the jam game does not model the spot: the chip chart path stays. +fn icm_push_fold_plan(spot: &Spot, lage: &Turnierlage, exploit: &Thresholds) -> Option { + let answer = push_fold(spot, lage)?; + let hand = percentile(spot.variant, &spot.hero_cards); + let scale = scale_for(spot, situation_of(spot), exploit); + let (aggressive, verb) = if answer.facing_jam { (ChartAction::Call, "call") } else { (ChartAction::Jam, "jam") }; + let equilibrium = if answer.continue_ { aggressive } else { ChartAction::Fold }; + let action = exploit_border(equilibrium, aggressive, hand, answer.width, scale); + let said = if action == ChartAction::Fold { "fold" } else { verb }; + let moved = if action == equilibrium { String::new() } else { format!(", exploit width {scale:.2} -> {said}") }; + Some(PreflopPlan { + action, + percentile: hand, + certainty: certainty(hand, &[answer.width * scale]), + reason: format!( + "ICM push/fold {:.1}bb vs {} {}: {} (equilibrium {verb}s {:.0}%, ICM edge {:+.4}){moved}", + answer.depth_bb, + answer.callers, + if answer.callers == 1 { "caller" } else { "callers" }, + if answer.continue_ { verb } else { "fold" }, + 100.0 * answer.width, + answer.edge, + ), + }) +} + +fn think(spot: &Spot, premium: f64, jam_widen: f64, raw: &Spot, lage: Option<&Turnierlage>) -> Decision { let profiles: Vec = spot.live_villains().filter_map(|v| v.profile).collect(); - let thresholds = with_premium(adjust(Thresholds::BASE, &profiles), premium); + let exploit = adjust(Thresholds::BASE, &profiles); + let thresholds = with_premium(exploit, premium); match spot.street { Street::Preflop => { - let plan = advise_widened(spot, &thresholds, jam_widen); + let plan = lage + .and_then(|l| icm_push_fold_plan(spot, l, &exploit)) + .unwrap_or_else(|| advise_widened(spot, &thresholds, jam_widen)); // Eine Grenzhand folgt ihrer Seite der Tabelle (Raise bleibt Raise, Call bleibt Call): // nahe der Grenze ist jede Linie fast gleich viel wert, Aussetzen ist die schlechteste. let certainty = plan.certainty.max(MIN_CERTAINTY); @@ -167,7 +204,7 @@ pub fn decide_with(spot: &Spot, lage: Option<&Turnierlage>) -> Decision { .map(jam_width_factor) .map(|w| 1.0 + (w - 1.0) * jam_depth_gate(spot.hero_stack / spot.big_blind)) .unwrap_or(1.0); - let decision = enforce(spot, think(spot, premium, jam_widen, raw)); + let decision = enforce(spot, think(spot, premium, jam_widen, raw, lage)); match crate::hand::showdown::best(spot.rules().hole_usage, &spot.hero_cards, &spot.board) { Ok(strength) => decision.with_category(strength.category), Err(_) => decision, diff --git a/src/icm/mod.rs b/src/icm/mod.rs index 22c4c9bb..341ed98d 100644 --- a/src/icm/mod.rs +++ b/src/icm/mod.rs @@ -20,4 +20,5 @@ pub mod harville; pub mod lage; +pub mod push_fold; pub mod risk; diff --git a/src/icm/push_fold.rs b/src/icm/push_fold.rs new file mode 100644 index 00000000..a0bd5782 --- /dev/null +++ b/src/icm/push_fold.rs @@ -0,0 +1,505 @@ +//! ICM push/fold: the short-stack all-in game solved in PRIZE money, antes included. +//! +//! Two preflop spots of a tournament table are the whole game at short depth: +//! * hero FIRST IN at or below `OPEN_JAM_MAX_BB` effective: jam or fold; +//! * hero FACING the lone jam of the first raiser (no caller in between) at or below +//! `CALL_JAM_MAX_BB`: call or fold. +//! +//! Both are one `JamGame`: a pusher, then the players behind it who may call, in acting order. +//! The game is solved by fictitious play over the 169 hand classes on the engine's own all-in +//! equity table (`cfr::generated_equity`), with every terminal valued by Malmuth-Harville +//! (`harville::equities`) over the WHOLE field under the pay structure: +//! * all fold: the pusher takes the pot (blinds AND antes - the dead money that makes short +//! stacks jam wide); +//! * caller `i` calls (the callers before it folded, the ones after fold too - no overcalls): a +//! heads-up all-in for `min(pusher, caller)` plus the dead money of everybody else; +//! * the pusher folds (hero first in): hero keeps what it has not posted, the big blind takes +//! the rest. +//! +//! The caller's fold value is the all-fold terminal. Card removal and overcalls are ignored (the +//! standard ICM push/fold approximation, as in `entscheiden/turnier_referenz.nash_icm_push`, +//! which this generalises from one bystander and heads-up to any field and table). +//! +//! The answer is the best response of HERO's actual class against the equilibrium of the other +//! side, plus the equilibrium width (share of combos that jam / call) - the base the exploit width +//! may move (`preflop::exploit_border`), exactly as the frozen chip tables do in cash. +//! +//! Only with a `Turnierlage`: cash never reaches this module (`engine::decide` calls it only +//! when the request carries `tournament`). Anything the game cannot model (limps, several +//! raises, a caller before hero, a field larger than `MAX_FIELD`, other variants) returns `None` +//! and the calibrated chip path with its ICM premium (`icm::risk`) stays in charge. + +use super::harville::equities; +use super::lage::Turnierlage; +use crate::cfr::equity_matrix::EquityMatrix; +use crate::cfr::frozen_equity::frozen_equity; +use crate::cfr::hand_class::{class_combos, class_of, CLASS_COUNT}; +use crate::game::{SeenAction, Spot, Street}; +use crate::preflop::effective_stack::effective_stack_bb; +use crate::preflop::first_raiser::{preflop_callers, raise_count, sole_raiser}; +use crate::variant::Variant; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::OnceLock; + +/// Measurement switch (always on in play): the strength ladder turns the solver off for the +/// paired A/B against the calibrated chip path (`sim::turnier_leiter::messen_solver`). +static ENABLED: AtomicBool = AtomicBool::new(true); + +/// Turns the solver on or off for this process (ladder A/B only). +pub fn set_enabled(on: bool) { + ENABLED.store(on, Ordering::Relaxed); +} + +/// Hero first in at or below this effective depth (big blinds) is a push/fold spot. +pub const OPEN_JAM_MAX_BB: f64 = 15.0; +/// Hero facing a lone jam at or below this effective depth is solved as a call/fold spot +/// (the same depth the frozen chip tables use for calling jams). +pub const CALL_JAM_MAX_BB: f64 = 25.0; +/// Largest field the solver prices (each terminal is one Harville evaluation; above +/// `harville::MAX_PLAYERS` it is sampled, 20 000 orders x field). +pub const MAX_FIELD: usize = 200; +/// Fictitious-play rounds; the average strategy moves by `1 / (t + 2)`. +pub const ROUNDS: usize = 150; +/// A busted stack is priced at this (Harville needs a positive rate; it finishes last). +const BUST_FLOOR: f64 = 1e-9; + +/// What hero should do, and how wide the equilibrium continues for hero's side. +#[derive(Clone, Debug, PartialEq)] +pub struct PushFoldAnswer { + /// Jam (first in) or call (facing a jam) is worth more prize money than folding. + pub continue_: bool, + /// Hero facing a jam (`true`) or first in (`false`). + pub facing_jam: bool, + /// Share of combos hero's side continues with at equilibrium (jam or call). + pub width: f64, + /// Prize money of continuing minus folding for hero's class (pool units of `payouts`). + pub edge: f64, + /// Effective depth in big blinds. + pub depth_bb: f64, + /// Number of modelled callers behind the pusher. + pub callers: usize, +} + +struct Table { + eq: Vec, + weight: [f64; CLASS_COUNT], +} + +fn table() -> &'static Table { + static T: OnceLock = OnceLock::new(); + T.get_or_init(|| { + let m: EquityMatrix = frozen_equity(); + let mut eq = vec![0.5; CLASS_COUNT * CLASS_COUNT]; + for i in 0..CLASS_COUNT { + for j in 0..CLASS_COUNT { + eq[i * CLASS_COUNT + j] = m.get(i, j); + } + } + let mut weight = [0.0; CLASS_COUNT]; + for (c, w) in weight.iter_mut().enumerate() { + *w = class_combos(c).len() as f64; + } + Table { eq, weight } + }) +} + +/// Prize values of the terminals, for the pusher and each caller. +#[derive(Clone, Debug, PartialEq)] +pub struct Terminals { + /// Pusher's money when everybody folds. + pub pusher_all_fold: f64, + /// Pusher's money when it folds itself (only meaningful when hero is the pusher). + pub pusher_fold: f64, + /// Per caller: (pusher wins, pusher loses) for the pusher. + pub pusher_vs: Vec<(f64, f64)>, + /// Per caller: (fold = all fold, call and win, call and lose) for the caller. + pub caller: Vec<(f64, f64, f64)>, +} + +/// One modelled player of the hand: index into the priced stacks, chips at hand start, forced +/// chips posted (blinds and antes). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Seat { + pub index: usize, + pub start: f64, + pub posted: f64, +} + +/// The terminals of the jam game. `stacks` is the field at hand start (table players' entries +/// already their hand-start chips), `forced` the forced pot (all blinds and antes), `bb_index` +/// the player that takes the pot when the pusher folds. +pub fn terminals( + stacks: &[f64], + payouts: &[f64], + pusher: Seat, + callers: &[Seat], + table_posts: &[Seat], + forced: f64, + bb_index: usize, +) -> Terminals { + // Everybody at the table loses what it posted; the field away from the table is untouched. + let base = || { + let mut s = stacks.to_vec(); + for p in table_posts { + s[p.index] = p.start - p.posted; + } + s + }; + let money = |s: &[f64]| { + let priced: Vec = s.iter().map(|x| x.max(BUST_FLOOR)).collect(); + equities(&priced, payouts) + }; + let mut all_fold = base(); + all_fold[pusher.index] += forced; + let v_all = money(&all_fold); + let mut folded = base(); + folded[bb_index] += forced; + let v_fold = money(&folded); + let mut pusher_vs = Vec::with_capacity(callers.len()); + let mut caller = Vec::with_capacity(callers.len()); + for c in callers { + let risk = pusher.start.min(c.start); + let dead = forced - pusher.posted - c.posted; + let mut win = base(); + win[pusher.index] = pusher.start + risk + dead; + win[c.index] = c.start - risk; + let mut lose = base(); + lose[pusher.index] = pusher.start - risk; + lose[c.index] = c.start + risk + dead; + let (w, l) = (money(&win), money(&lose)); + pusher_vs.push((w[pusher.index], l[pusher.index])); + caller.push((v_all[c.index], l[c.index], w[c.index])); + } + Terminals { pusher_all_fold: v_all[pusher.index], pusher_fold: v_fold[pusher.index], pusher_vs, caller } +} + +/// Equilibrium of the jam game: (push frequency per class, call frequency per class per caller). +pub fn solve(t: &Terminals) -> (Vec, Vec>) { + let tab = table(); + let k = t.caller.len(); + let mut push = vec![1.0; CLASS_COUNT]; + let mut call = vec![vec![0.0; CLASS_COUNT]; k]; + for round in 0..ROUNDS { + let step = 1.0 / (round as f64 + 2.0); + // Callers: best response to the average push range. + let push_mass: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h]).sum(); + let mut call_br = vec![vec![0.0; CLASS_COUNT]; k]; + if push_mass > 0.0 { + for c in 0..CLASS_COUNT { + let row = &tab.eq[c * CLASS_COUNT..(c + 1) * CLASS_COUNT]; + let e: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h] * row[h]).sum::() / push_mass; + for (i, &(fold, win, lose)) in t.caller.iter().enumerate() { + if e * win + (1.0 - e) * lose > fold { + call_br[i][c] = 1.0; + } + } + } + } + // Pusher: best response to the average call ranges. + let push_br = pusher_best_response(t, &call, tab); + for c in 0..CLASS_COUNT { + push[c] += (push_br[c] - push[c]) * step; + for i in 0..k { + call[i][c] += (call_br[i][c] - call[i][c]) * step; + } + } + } + (push, call) +} + +/// Prize money of jamming each class against the call ranges. +fn push_values(t: &Terminals, call: &[Vec], tab: &Table) -> Vec { + let total: f64 = tab.weight.iter().sum(); + let mut value = vec![0.0; CLASS_COUNT]; + let mut reach = 1.0; + for (i, range) in call.iter().enumerate() { + let mass: f64 = (0..CLASS_COUNT).map(|c| range[c] * tab.weight[c]).sum(); + let q = mass / total; + let (win, lose) = t.pusher_vs[i]; + for (h, v) in value.iter_mut().enumerate() { + let e = if mass > 0.0 { + let row = &tab.eq[h * CLASS_COUNT..(h + 1) * CLASS_COUNT]; + (0..CLASS_COUNT).map(|c| range[c] * tab.weight[c] * row[c]).sum::() / mass + } else { + 0.5 + }; + *v += reach * q * (e * win + (1.0 - e) * lose); + } + reach *= 1.0 - q; + } + for v in &mut value { + *v += reach * t.pusher_all_fold; + } + value +} + +fn pusher_best_response(t: &Terminals, call: &[Vec], tab: &Table) -> Vec { + push_values(t, call, tab).iter().map(|v| if *v > t.pusher_fold { 1.0 } else { 0.0 }).collect() +} + +fn share(range: &[f64], tab: &Table) -> f64 { + let total: f64 = tab.weight.iter().sum(); + (0..CLASS_COUNT).map(|c| range[c].round() * tab.weight[c]).sum::() / total +} + +/// Hero's chips at hand start: what the field lists for hero. +fn hand_start(lage: &Turnierlage) -> f64 { + lage.stacks[lage.hero] +} + +/// Forced chips a seat posted this hand (blinds and antes). +fn posted(spot: &Spot, seat: u8) -> f64 { + let preflop = || spot.history.iter().filter(move |r| r.street == Street::Preflop && r.seat == seat); + let ante: f64 = preflop().filter(|r| r.action == SeenAction::PostAnte).filter_map(|r| r.amount).sum(); + let blind = preflop() + .filter(|r| matches!(r.action, SeenAction::PostSmallBlind | SeenAction::PostBigBlind)) + .filter_map(|r| r.amount) + .fold(0.0, f64::max); + ante + blind +} + +/// Everything a seat put in this hand so far (antes plus its street total preflop). +fn committed(spot: &Spot, seat: u8) -> f64 { + let preflop = || spot.history.iter().filter(move |r| r.street == Street::Preflop && r.seat == seat); + let ante: f64 = preflop().filter(|r| r.action == SeenAction::PostAnte).filter_map(|r| r.amount).sum(); + let street = preflop().filter(|r| r.action != SeenAction::PostAnte).filter_map(|r| r.amount).fold(0.0, f64::max); + ante + street +} + +/// Who posted the big blind (takes the pot when the pusher folds). +fn big_blind_seat(spot: &Spot) -> Option { + spot.history + .iter() + .find(|r| r.street == Street::Preflop && r.action == SeenAction::PostBigBlind) + .map(|r| r.seat) +} + +/// Acting order after `from` around the ring of `seats`. +fn after(seats: u8, from: u8, seat: u8) -> u8 { + let n = seats.max(1); + ((seat + n - from) % n).max(1) +} + +/// The field with each table villain's entry replaced by its hand-start chips: villains are +/// matched to the nearest unmatched field stack (the rank list lags the table a little); a +/// villain without a match is appended. +fn place_villains(lage: &Turnierlage, table: &[(u8, f64)]) -> (Vec, Vec<(u8, usize)>) { + let mut stacks = lage.stacks.clone(); + let mut taken = vec![false; stacks.len()]; + taken[lage.hero] = true; + let mut placed = Vec::with_capacity(table.len()); + for &(seat, start) in table { + let best = (0..stacks.len()) + .filter(|i| !taken[*i]) + .min_by(|a, b| (lage.stacks[*a] - start).abs().total_cmp(&(lage.stacks[*b] - start).abs())); + let index = match best { + Some(i) => i, + None => { + stacks.push(start); + taken.push(false); + stacks.len() - 1 + } + }; + taken[index] = true; + stacks[index] = start; + placed.push((seat, index)); + } + (stacks, placed) +} + +/// The ICM push/fold answer for hero, or `None` when the spot is not a modelled jam game. +pub fn push_fold(spot: &Spot, lage: &Turnierlage) -> Option { + if !ENABLED.load(Ordering::Relaxed) { + return None; + } + if !lage.is_usable() || lage.stacks.len() > MAX_FIELD || spot.street != Street::Preflop { + return None; + } + if !matches!(spot.variant, Variant::Nlhe | Variant::Aof) || spot.hero_cards.len() != 2 { + return None; + } + if !(spot.big_blind.is_finite() && spot.big_blind > 0.0) || !preflop_callers(spot).is_empty() { + return None; + } + let hero_class = class_of(spot.hero_cards[0], spot.hero_cards[1])?; + let big_blind = big_blind_seat(spot)?; + let hero_start = hand_start(lage); + // Every seat dealt in that the history or the villains name; folded villains still posted. + let mut seats: Vec = spot.villains.iter().map(|v| v.seat).collect(); + for r in spot.history.iter().filter(|r| r.street == Street::Preflop) { + if r.seat != spot.hero_seat && !seats.contains(&r.seat) { + seats.push(r.seat); + } + } + let stack_of = |seat: u8| spot.villains.iter().find(|v| v.seat == seat).map(|v| v.stack); + let table_starts: Vec<(u8, f64)> = + seats.iter().filter_map(|s| stack_of(*s).map(|st| (*s, st + committed(spot, *s)))).collect(); + let (mut stacks, placed) = place_villains(lage, &table_starts); + stacks[lage.hero] = hero_start; + let stacks = stacks; + let index_of = |seat: u8| -> Option { + if seat == spot.hero_seat { + Some(lage.hero) + } else { + placed.iter().find(|(s, _)| *s == seat).map(|(_, i)| *i) + } + }; + let seat_of = |seat: u8| -> Option { + let index = index_of(seat)?; + Some(Seat { index, start: stacks[index], posted: posted(spot, seat) }) + }; + let hero = Seat { index: lage.hero, start: hero_start, posted: posted(spot, spot.hero_seat) }; + let table_posts: Vec = + std::iter::once(hero).chain(seats.iter().filter_map(|s| seat_of(*s))).collect(); + let forced: f64 = table_posts.iter().map(|p| p.posted).sum(); + let bb_index = index_of(big_blind)?; + let folded_before = |seat: u8, jam_at: usize| { + spot.history.iter().take(jam_at).any(|r| r.seat == seat && r.action == SeenAction::Fold) + }; + match raise_count(spot) { + 0 => { + // First in: hero pushes, every live villain may call, in acting order. + let depth = effective_stack_bb(spot); + if depth > OPEN_JAM_MAX_BB || !spot.history.iter().any(|r| r.action == SeenAction::PostBigBlind) { + return None; + } + if spot.to_call > spot.big_blind + 1e-9 || big_blind == spot.hero_seat { + return None; // a limp or hero's own option: not a first-in jam + } + let mut behind: Vec<&crate::game::Villain> = spot.live_villains().collect(); + behind.sort_by_key(|v| after(spot.seats, spot.hero_seat, v.seat)); + let callers: Vec = behind.iter().filter_map(|v| seat_of(v.seat)).collect(); + if callers.is_empty() || callers.len() != behind.len() { + return None; + } + let t = terminals(&stacks, &lage.payouts, hero, &callers, &table_posts, forced, bb_index); + let (_, call) = solve(&t); + let tab = table(); + let values = push_values(&t, &call, tab); + let br: Vec = values.iter().map(|v| if *v > t.pusher_fold { 1.0 } else { 0.0 }).collect(); + let edge = values[hero_class] - t.pusher_fold; + Some(PushFoldAnswer { + continue_: edge > 0.0, + facing_jam: false, + width: share(&br, tab), + edge, + depth_bb: depth, + callers: callers.len(), + }) + } + 1 => { + // Facing the lone jam of the first raiser. + let jammer = sole_raiser(spot)?; + let jam_at = spot + .history + .iter() + .position(|r| r.street == Street::Preflop && r.seat == jammer && r.action.is_aggressive())?; + let jam = spot.history[jam_at]; + let jammer_stack = stack_of(jammer)?; + let all_in = jam.action == SeenAction::AllIn || jammer_stack <= 1e-9; + if !all_in || spot.to_call <= 0.0 { + return None; + } + let pusher = seat_of(jammer)?; + let depth = pusher.start.min(hero_start) / spot.big_blind; + if depth > CALL_JAM_MAX_BB { + return None; + } + // The players behind the jammer when it jammed: hero first (it acts now), then the + // live villains still to act; who folded before the jam was not behind it. + let mut behind: Vec = seats + .iter() + .copied() + .filter(|s| *s != jammer && !folded_before(*s, jam_at)) + .filter(|s| { + spot.villains.iter().any(|v| v.seat == *s && !v.folded) + || spot.history.iter().skip(jam_at).any(|r| r.seat == *s && r.action == SeenAction::Fold) + }) + .collect(); + behind.sort_by_key(|s| after(spot.seats, jammer, *s)); + let mut callers: Vec = vec![hero]; + callers.extend(behind.iter().filter(|s| **s != spot.hero_seat).filter_map(|s| seat_of(*s))); + callers.sort_by_key(|c| { + let seat = if c.index == hero.index { + spot.hero_seat + } else { + placed.iter().find(|(_, i)| *i == c.index).map_or(spot.hero_seat, |(s, _)| *s) + }; + after(spot.seats, jammer, seat) + }); + let me = callers.iter().position(|c| c.index == hero.index)?; + let t = terminals(&stacks, &lage.payouts, pusher, &callers, &table_posts, forced, bb_index); + let (push, call) = solve(&t); + let tab = table(); + let mass: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h]).sum(); + if mass <= 0.0 { + return None; + } + let row = &tab.eq[hero_class * CLASS_COUNT..(hero_class + 1) * CLASS_COUNT]; + let e: f64 = (0..CLASS_COUNT).map(|h| push[h] * tab.weight[h] * row[h]).sum::() / mass; + let (fold, win, lose) = t.caller[me]; + let edge = e * win + (1.0 - e) * lose - fold; + Some(PushFoldAnswer { + continue_: edge > 0.0, + facing_jam: true, + width: share(&call[me], tab), + edge, + depth_bb: depth, + callers: callers.len(), + }) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hu(hero: f64, opp: f64, field: &[f64]) -> (Vec, Seat, Seat) { + let mut stacks = vec![hero, opp]; + stacks.extend_from_slice(field); + (stacks, Seat { index: 0, start: hero, posted: 0.5 }, Seat { index: 1, start: opp, posted: 1.0 }) + } + + fn widths(payouts: &[f64], hero: f64, opp: f64, field: &[f64]) -> (f64, f64) { + let (stacks, p, c) = hu(hero, opp, field); + let t = terminals(&stacks, payouts, p, &[c], &[p, c], 1.5, 1); + let (push, call) = solve(&t); + let tab = table(); + (share(&push, tab), share(&call[0], tab)) + } + + #[test] + fn winner_take_all_heads_up_is_the_chip_nash() { + // One prize, two players: ICM money IS the chip share - the solver is chip Nash. HU 10bb: + // jam ~60 %, call ~38 % (the frozen chip tables, `push_chart` and turnier_referenz). + let (jam, call) = widths(&[1.0], 10.0, 10.0, &[]); + assert!((jam - 0.60).abs() < 0.05, "chip-Nash jam ~60 %: {jam}"); + assert!((call - 0.38).abs() < 0.05, "chip-Nash call ~38 %: {call}"); + } + + #[test] + fn bubble_with_a_short_bystander_matches_the_icm_nash_reference() { + // entscheiden/turnier_referenz.nash_icm_push, HU 10bb/10bb, 50/30/20, short bystander + // 2/5/9bb: ICM-Nash jam 97/79/65 %, call 14/18/22 %. Frozen anchor, +-5pp. + for (short, jam_ref, call_ref) in [(2.0, 0.97, 0.14), (5.0, 0.79, 0.18), (9.0, 0.65, 0.22)] { + let (jam, call) = widths(&[50.0, 30.0, 20.0], 10.0, 10.0, &[short]); + assert!((jam - jam_ref).abs() < 0.05, "short {short}: jam {jam} vs {jam_ref}"); + assert!((call - call_ref).abs() < 0.05, "short {short}: call {call} vs {call_ref}"); + } + } + + #[test] + fn antes_widen_the_jam() { + // The same 10bb heads-up with 1.2bb of antes in the middle: more dead money, wider jam. + let (stacks, p, c) = hu(10.0, 10.0, &[]); + let plain = terminals(&stacks, &[1.0], p, &[c], &[p, c], 1.5, 1); + let p_a = Seat { posted: 0.5 + 0.6, ..p }; + let c_a = Seat { posted: 1.0 + 0.6, ..c }; + let ante = terminals(&stacks, &[1.0], p_a, &[c_a], &[p_a, c_a], 2.7, 1); + let tab = table(); + let (a, b) = (share(&solve(&plain).0, tab), share(&solve(&ante).0, tab)); + assert!(b > a + 0.05, "antes widen the jam: {a} -> {b}"); + } +} diff --git a/src/preflop/advise.rs b/src/preflop/advise.rs index 074852c7..00493bb5 100644 --- a/src/preflop/advise.rs +++ b/src/preflop/advise.rs @@ -72,7 +72,7 @@ fn cutoffs(spot: &Spot, situation: Situation, effective_bb: f64, scale: f64, jam /// Width multiplier for this situation: `range_width_scale` (the profile shift), and in /// unopened pots, which are steals, also how often the players behind fold /// (`exploit::steal_width`: wider against nits, narrower against calling stations). -fn scale_for(spot: &Spot, situation: Situation, thresholds: &Thresholds) -> f64 { +pub(crate) fn scale_for(spot: &Spot, situation: Situation, thresholds: &Thresholds) -> f64 { let shift = sane_scale(thresholds.range_width_scale); match situation { Situation::Unopened => shift * steal_width(spot), diff --git a/src/sim/turnier_leiter.rs b/src/sim/turnier_leiter.rs index 5c2a98f6..bd0e493a 100644 --- a/src/sim/turnier_leiter.rs +++ b/src/sim/turnier_leiter.rs @@ -189,6 +189,61 @@ pub fn messen(s: &Szenario) -> TurnierMessung { } } +/// Paired A/B of the ICM push/fold solver (`icm::push_fold`): BOTH lines play the tournament +/// (`Some(lage)`), line A with the solver, line B with it switched off (the calibrated chip path +/// with its ICM premium). Same deals and seats, so the edge is the solver's own contribution in +/// ICM money. `icm_on_per100` = solver, `icm_off_per100` = calibrated path. Single-threaded: the +/// switch is process-wide. +pub fn messen_solver(s: &Szenario) -> TurnierMessung { + let lage = lage_of(s); + let mut edge = Vec::with_capacity(s.deals as usize); + let (mut on_tot, mut off_tot) = (0.0, 0.0); + let (mut decisions, mut abstains, mut invalid, mut hands) = (0u32, 0u32, 0u32, 0u32); + for d in 0..s.deals { + let (cards, _) = deal(2, Rng::seeded(mix(s.seed, d as u64))); + let mut e = 0.0; + for hero_seat in 1..=2u8 { + let setup = HandSetup { + deal: &cards, + hero_seat, + opponent: s.opponent, + stack_bb: s.hero_stack, + seed: mix(s.seed ^ 0xA5A5, (d as u64) << 8 | hero_seat as u64), + read: HandRead::Oracle, + }; + let start = if hero_seat == 1 { [s.hero_stack, s.opp_stack] } else { [s.opp_stack, s.hero_stack] }; + crate::icm::push_fold::set_enabled(true); + let on = play_hand_seated(&setup, &start, Some(&lage)); + crate::icm::push_fold::set_enabled(false); + let off = play_hand_seated(&setup, &start, Some(&lage)); + crate::icm::push_fold::set_enabled(true); + let s_on = icm_score(&lage, on.hero_net); + let s_off = icm_score(&lage, off.hero_net); + e += s_on - s_off; + on_tot += s_on; + off_tot += s_off; + decisions += on.hero_decisions + off.hero_decisions; + abstains += on.abstains + off.abstains; + invalid += on.invalid + off.invalid; + hands += 1; + } + edge.push(e / 2.0); + } + let (edge_per100, ci95) = rate(&edge); + let n = f64::from(s.deals.max(1) * 2); + TurnierMessung { + name: s.name, + hands, + icm_on_per100: 100.0 * on_tot / n, + icm_off_per100: 100.0 * off_tot / n, + edge_per100, + ci95, + decisions, + abstains, + invalid, + } +} + /// Mean and 95 % half width of per-deal samples, both scaled to "per 100 hands". fn rate(samples: &[f64]) -> (f64, f64) { let n = samples.len().max(1) as f64; diff --git a/tests/turnier_anfrage_spec.py b/tests/turnier_anfrage_spec.py index 093fe7e9..f6a9ec22 100644 --- a/tests/turnier_anfrage_spec.py +++ b/tests/turnier_anfrage_spec.py @@ -1,268 +1,311 @@ -#!/usr/bin/env python3 -"""Spezifikation: die Turnierlage geht mit der Anfrage zum Kern (Feld `tournament`). - -Form (Erweiterung wie `history`, nicht in VERTRAG.md; der Kern liest sie in wire/decode_tournament): - "tournament": {"payouts": [Betrag Platz 1, 2,...], "stacks": [wir, dann das Feld], - "heroIndex": 0, "ante": a, "level": l} - -Fälle: - * Turniertisch + Lobby-Meldungen VOR dem Zug -> `tournament`: - payouts = `prizeList[].amount` nach Rang 1..n (Geld) - stacks = [unser Stapel bei Handbeginn] + jeder `rankList`-Eintrag mit Chips > 0 ausser uns - unser Stapel bei Handbeginn = Tisch-Chips + Antes + je Straße der höchste eigene Einsatz - ante, level = `currentBlindLevel` der letzten dynamic_lobby_data - * Welche Lobby zum Tisch gehört: `tourneyTableProperties.tourneyLobbyName` aus game_alldata, - sonst `Comm_Tournament_` (tournamentId > 0). ANNAHME: Im Bestand gibt es keinen - Turniertisch (alle 18 game_alldata sind Ring, tournamentId 0) - die Felder selbst sind. - * Turniertisch, aber Preise oder Rangliste fehlen noch -> aussetzen, `_unklar` "Turnier:...": - ohne Lage wäre jede Turnierentscheidung geraten. - * Meldungen NACH dem Zug zählen für diesen Zug nicht. - * Cash-Tisch (tournamentId 0, kein Lobbyname) -> kein `tournament`, Anfrage unverändert. - * gameType "Tournament" mit miniGameTypeId 1 ist NLHE (wie Ring); "Allinfold" ist eine - Ueberlagerung dieser Basisart: NLHE, aber nur Fold/All-in (legalActions ["FOLD", "RAISE"]). - * Ende zu Ende mit dem Kern: Lobbyzeilen aus dem Bestand (turnier-bubble: 15 im Feld, 14 bezahlt), - dieselbe Hand ohne Lobby: im Turnier callt der BB den Shove mit weniger Händen als im Cash. - - python3 tests/turnier_anfrage_spec.py -v -""" -import json -import os -import sys -import unittest - -_w = os.path.dirname(os.path.abspath(__file__)) -while _w != "/" and not os.path.isdir(os.path.join(_w, "lesen")): - _w = os.path.dirname(_w) -for _u in ("lesen", "entscheiden", "hand", "client"): - sys.path.insert(0, os.path.join(_w, _u)) - -import decide -import spot_from_log - -LOBBY = "Comm_Tournament_117632" -TISCH = "₮1.10 6-Max Hyper 117632 Tisch 3" -HAND = "11763200019" -HELD = "Williamson1986" # 20205.88 Chips in der Rangliste -with open(os.path.join(_w, "archiv", "mitschrieb", "beispiele", "turnier-bubble.txt"), encoding="utf-8") as _f: - BUBBLE = _f.read() # Lobbyzeilen: Level 19 (1250/2500/312), 15 im Feld, 14 bezahlt -PREISE = [27.76, 18.28, 12.22, 8.38, 5.96, 4.45, 3.49, 2.89, 2.89, 2.48, 2.48, 2.19, 2.19, 2.19] -FELD_OHNE_UNS = [181821.41, 62866.91, 47562.93, 42266.69, 41797.34, 41582.58, 31898.98, 30676.8, - 30466.03, 27140.76, 25802.0, 24046.68, 22206.0, 20330.29, 14328.72] - - -def zeile(cmd, daten, raum=TISCH): - daten = dict(daten, gameHandId=daten.get("gameHandId", HAND)) - bohne = json.dumps(json.dumps(daten, separators=(",", ":")))[1:-1] - return ('2026-10-28 12:00:00:000 [info] [UNITY] Stdout: [Method] -> SendMessageToPipe - ' - '{"EventName":"extension_event","RequestId":null,"Data":{"cmd_bean":{"BeanData":"' - + bohne + f'","Cmd":"{cmd}","RoomName":"{raum}"}},"room_name":"{raum}"}}}}\n') - - -def karte(wert, farbe): - return {"suit": farbe, "value": wert} - - -def alldata(lobby=LOBBY, nummer=117632, game_type="Tournament"): - sitze = [{"seatId": 3, "userName": HELD, "userChips": 20205.88, "isPlaying": True}, - {"seatId": 2, "userName": "Leander77", "userChips": 20330.29, "isPlaying": True}, - {"seatId": 1, "userName": "QaQom", "userChips": 42266.69, "isPlaying": True}] - return zeile("game.game_alldata", { - "gameInitResponseData": {"bigBlind": 2500.0, "dealerSeatId": 1, "gameHandId": None}, - "seatInfoRsponseData": {"isGameStarted": False, "seatResponseDataList": sitze}, - "roomProperties": {"gameType": game_type, "miniGameTypeId": 1, "tournamentType": "TOURNAMENT"}, - "tourneyTableProperties": {"tournamentId": nummer, "tourneyLobbyName": lobby}}) - - -def alldata_ohne_lobby(): - """game_alldata mit gameType 'Tournament', aber OHNE tourneyTableProperties: die Beitritts-Zeile - ist aus dem 4-MB-Tail gescrollt, self.lobby bleibt None. Die Uebersetzung muss TROTZDEM greifen - - sonst setzt die Engine aus und der Laeufer foldet/checkt blind (Owner 9.11.: JJ pot-committed weg).""" - sitze = [{"seatId": 3, "userName": HELD, "userChips": 20205.88, "isPlaying": True}, - {"seatId": 2, "userName": "Leander77", "userChips": 20330.29, "isPlaying": True}, - {"seatId": 1, "userName": "QaQom", "userChips": 42266.69, "isPlaying": True}] - return zeile("game.game_alldata", { - "gameInitResponseData": {"bigBlind": 2500.0, "dealerSeatId": 1, "gameHandId": None}, - "seatInfoRsponseData": {"isGameStarted": False, "seatResponseDataList": sitze}, - "roomProperties": {"gameType": "Tournament", "miniGameTypeId": 1, "tournamentType": "TOURNAMENT"}}) - - -def hand(loch=(karte("ACE", "SPADES"), karte("NINE", "HEARTS")), gameHandId=HAND): - """Antes, SB 1250, BB 2500 (wir), Knopf foldet, SB schiebt 20018.29 (alles), wir am Zug.""" - h = {"gameHandId": gameHandId} - text = zeile("game.pre_hand_start_info", dict(h, dealerSeatId=1, bbAmount=2500.0, sbAmount=1250.0, - anteAmount=312.0)) - for sitz, name, nach in ((3, HELD, 19893.88), (2, "Leander77", 20018.29), (1, "QaQom", 41954.69)): - text += zeile("game.seat", dict(h, seatId=sitz, userName=name, caption="Ante", betAmout=312.0, - userChips=nach)) - text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="SB", betAmout=1250.0, - userChips=18768.29)) - text += zeile("game.seat", dict(h, seatId=3, userName=HELD, caption="BB", betAmout=2500.0, - userChips=17393.88)) - text += zeile("game.seat", dict(h, seatId=1, userName="QaQom", caption="Fold", betAmout=0.0, - userChips=41954.69)) - text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="AllIn", betAmout=20018.29, - userChips=0.0)) - text += zeile("game.hole_cards", dict(h, holeCards=list(loch))) - return text - - -def zug(gameHandId=HAND): - return zeile("game.user_turn", { - "gameHandId": gameHandId, "userTurnOptions": {"3": [], "4": [17393.88], "6": [], "5": [], "7": None}, - "whoseTurn": HELD, "turnTime": 16, "callAmount": 17393.88, "totalPot": 23454.29, - "extraTurnTime": 0, "extraTimerEnabled": False, "kpokerActions": None}) - - -def anfragen(text): - return [json.loads(z) for z, _, _, _, _ in spot_from_log.spots(text)] - - -class Lage(unittest.TestCase): - def setUp(self): - self.a, = anfragen(alldata() + BUBBLE + hand() + zug()) - - def test_preise_nach_rang(self): - self.assertEqual(self.a["tournament"]["payouts"], PREISE) - - def test_stapel_wir_zuerst_bei_handbeginn(self): - t = self.a["tournament"] - self.assertEqual(t["heroIndex"], 0) - self.assertAlmostEqual(t["stacks"][0], 17393.88 + 312 + 2500, places=2) # = 20205.88 - self.assertEqual(sorted(t["stacks"][1:], reverse=True), FELD_OHNE_UNS) # Rangliste ohne uns, ohne 0-Chips - - def test_level_und_ante(self): - self.assertEqual((self.a["tournament"]["level"], self.a["tournament"]["ante"]), (19, 312)) - - def test_spielt_normal(self): - self.assertEqual(self.a["variant"], "NLHE") - self.assertEqual(self.a["legalActions"], ["FOLD", "CALL"]) - self.assertNotIn("_unklar", self.a) - - -class Zuordnung(unittest.TestCase): - def test_ueber_die_turniernummer(self): - a, = anfragen(alldata(lobby=None) + BUBBLE + hand() + zug()) - self.assertEqual(a["tournament"]["payouts"], PREISE) - - def test_fremde_lobby_gehoert_nicht_zum_tisch(self): - a, = anfragen(alldata(lobby="Comm_Tournament_999", nummer=999) + BUBBLE + hand() + zug()) - self.assertNotIn("tournament", a) - self.assertEqual(a["legalActions"], []) - self.assertTrue(a["_unklar"].startswith("Turnier: "), a["_unklar"]) - - def test_cash_tisch_bleibt_cash(self): - a, = anfragen(alldata(lobby=None, nummer=0, game_type="Ring") + BUBBLE + hand() + zug()) - self.assertNotIn("tournament", a) - self.assertEqual(a["legalActions"], ["FOLD", "CALL"]) - - def test_allinfold_ist_die_basisart_mit_fold_allin(self): - a, = anfragen(alldata(game_type="Allinfold") + BUBBLE + hand() + zug()) - self.assertEqual(a["variant"], "NLHE") - self.assertEqual(a["legalActions"], ["FOLD", "RAISE"]) - self.assertNotIn("_unklar", a) - - -class Reihenfolge(unittest.TestCase): - def test_meldungen_nach_dem_zug_zaehlen_nicht(self): - a, b = anfragen(alldata() + hand() + zug() + BUBBLE + hand(gameHandId="11763200020") - + zug(gameHandId="11763200020")) - self.assertEqual(a["legalActions"], []) - self.assertEqual(a["_unklar"], "Turnier: Preisliste fehlt") - self.assertEqual(b["tournament"]["payouts"], PREISE) - - def test_ohne_rangliste_aussetzen(self): - ohne = "".join(z for z in BUBBLE.splitlines(True) if "tournamentlobby.rank_list" not in z) - a, = anfragen(alldata() + ohne + hand() + zug()) - self.assertEqual(a["_unklar"], "Turnier: Rangliste fehlt") - - -RANG = "AKQJT98765432" -NAME = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT", - "7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"} - - -def haende(): - aus = [] - for i, a in enumerate(RANG): - for b in RANG[i:]: - zweite = "HEARTS" if a == b else "SPADES" - aus.append((karte(NAME[a], "SPADES"), karte(NAME[b], zweite))) - if a != b: - aus.append((karte(NAME[a], "SPADES"), karte(NAME[b], "HEARTS"))) - return aus - - -@unittest.skipUnless(decide.bereit(), "Kern nicht gebaut") -class EndeZuEnde(unittest.TestCase): - """Lobby (Bubble: 15 im Feld, 14 bezahlt), dieselbe Hand mit 169 Startkarten.""" - - def test_bubble_callt_enger_als_cash(self): - turnier, cash = [], [] - for n, loch in enumerate(haende()): - # Hand-IDs NACH der Beitrittszeile (alldata traegt HAND = ...0019): kleinere IDs sind fuer - # den Leser spaete Zeilen einer alten Hand - ohne Verlauf kein Angreifer, keine ICM-Praemie. - nr = f"1176321{n:04d}" - turnier.append(spot_from_log.spots(alldata() + BUBBLE + hand(loch, nr) + zug(nr))[0][0]) - cash.append(spot_from_log.spots(alldata(lobby=None, nummer=0, game_type="Ring") - + hand(loch, nr) + zug(nr))[0][0]) - self.assertTrue(all("tournament" in json.loads(z) for z in turnier)) - calls = [sum(a["action"] == "CALL" for a in decide.entscheide(z, timeout=300)) for z in (turnier, cash)] - print(f"\n8 BB im BB gegen Shove, 169 Hände: Turnier (Bubble) {calls[0]} Calls, Cash {calls[1]}") - self.assertLess(calls[0], calls[1]) - - -def zug_offen(gameHandId=HAND): - """Unser Zug am Turniertisch, nichts zu callen - mit dem ECHTEN Freeroll-Optionsformat - (live 9.11. gemessen): callAmount 0, "5" leer, "4" null, eigene Schluessel 7/8/9. Im Cash - stehen hier die Raise-Groessen in "5"; im Turnier nicht - der Parser fand darum nie ein RAISE.""" - return zeile("game.user_turn", { - "gameHandId": gameHandId, "whoseTurn": HELD, "turnTime": 16, "callAmount": 0.0, - "totalPot": 900.0, "extraTurnTime": 0, "extraTimerEnabled": False, "kpokerActions": None, - "userTurnOptions": {"3": [], "4": None, "6": [], "5": [], "7": [], "8": [], "9": []}}) - - -def hand_offen(loch=(karte("ACE", "SPADES"), karte("QUEEN", "HEARTS")), gameHandId=HAND): - """Wir sind BB mit Stapel, der SB limpt/ergaenzt - wir koennen checken ODER jammen (kein Shove gegen uns).""" - h = {"gameHandId": gameHandId} - text = zeile("game.pre_hand_start_info", dict(h, dealerSeatId=1, bbAmount=2500.0, sbAmount=1250.0)) - text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="SB", betAmout=1250.0, - userChips=18768.29)) - text += zeile("game.seat", dict(h, seatId=3, userName=HELD, caption="BB", betAmout=2500.0, - userChips=17393.88)) - text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="Call", betAmout=2500.0, - userChips=17518.29)) - text += zeile("game.hole_cards", dict(h, holeCards=list(loch))) - return text - - -class JamAmTurniertisch(unittest.TestCase): - """Am Turniertisch MUSS der Jam (All-in) verfuegbar sein: der Server listet die Raise-Groessen - nicht wie im Cash ("5" leer), sonst bekam der Bot nur Fold/Check und foldete/checkte JEDE Hand - (Owner 9.11.: 'er sitzt angemeldet, foldet aber alles; AQ -> Fold').""" - - def test_raise_als_jam_verfuegbar(self): - a, = anfragen(alldata_ohne_lobby() + hand_offen() + zug_offen()) - self.assertIn("RAISE", a["legalActions"]) - self.assertEqual(a["minRaiseTo"], a["heroStack"]) # Jam = All-in (ganzer Stapel) - self.assertEqual(a["maxRaiseTo"], a["heroStack"]) - - def test_cashtisch_bleibt_ohne_erfundenes_raise(self): - # derselbe leere Optionssatz an einem RING-Tisch: KEIN erfundenes RAISE (nur Turnier-Rueckfall) - a, = anfragen(alldata(lobby=None, nummer=0, game_type="Ring") + hand_offen() + zug_offen()) - self.assertNotIn("RAISE", a["legalActions"]) - - -class OhneBeitrittsZeile(unittest.TestCase): - """gameType 'Tournament', aber die Beitritts-Zeile (tourneyTableProperties) ist aus dem Tail - gescrollt - self.lobby None. Frueher setzte die Engine aus ('gameType Tournament nicht - abgebildet'), der Laeufer foldete/checkte blind (Owner 9.11.: JJ pot-committed weg, 180/910).""" - - def test_turniertisch_uebersetzt_auch_ohne_lobby(self): - a, = anfragen(alldata_ohne_lobby() + hand() + zug()) - self.assertEqual(a["variant"], "NLHE") # Turniertisch IST ein Pokertisch - self.assertTrue(a.get("legalActions")) # nicht leer = nicht ausgesetzt - self.assertNotIn("tournament", a) # ohne Lobby kein ICM-Feld - aber chip-EV spielt - - -if __name__ == "__main__": - unittest.main() +#!/usr/bin/env python3 +"""Spezifikation: die Turnierlage geht mit der Anfrage zum Kern (Feld `tournament`). + +Form (Erweiterung wie `history`, nicht in VERTRAG.md; der Kern liest sie in wire/decode_tournament): + "tournament": {"payouts": [Betrag Platz 1, 2,...], "stacks": [wir, dann das Feld], + "heroIndex": 0, "ante": a, "level": l} + +Fälle: + * Turniertisch + Lobby-Meldungen VOR dem Zug -> `tournament`: + payouts = `prizeList[].amount` nach Rang 1..n (Geld) + stacks = [unser Stapel bei Handbeginn] + jeder `rankList`-Eintrag mit Chips > 0 ausser uns + unser Stapel bei Handbeginn = Tisch-Chips + Antes + je Straße der höchste eigene Einsatz + ante, level = `currentBlindLevel` der letzten dynamic_lobby_data + * Welche Lobby zum Tisch gehört: `tourneyTableProperties.tourneyLobbyName` aus game_alldata, + sonst `Comm_Tournament_` (tournamentId > 0). ANNAHME: Im Bestand gibt es keinen + Turniertisch (alle 18 game_alldata sind Ring, tournamentId 0) - die Felder selbst sind. + * Turniertisch, aber Preise, Rangliste oder Lobby fehlen -> NICHT aussetzen (am echten Tisch hiesse das + blind folden/checken), sondern sicher Chip-EV: kein `tournament`, Leiste wie sonst, `_turnier` + "Chip-EV-Rückfall: Turnier: ..." nennt den Grund (decide.py haengt ihn an die Begruendung). + Mit Lage: `_turnier` "ICM". + * Die Lobby kommt auch auf dem TISCHkanal (`cmd_bean.Cmd` tournamentlobby.*, gemessen 04.11.): diese + Rahmen allein reichen fuer die Lage und machen den Tisch zum Turniertisch. + * Meldungen NACH dem Zug zählen für diesen Zug nicht. + * Cash-Tisch (tournamentId 0, kein Lobbyname) -> kein `tournament`, Anfrage unverändert. + * gameType "Tournament" mit miniGameTypeId 1 ist NLHE (wie Ring); "Allinfold" ist eine + Ueberlagerung dieser Basisart: NLHE, aber nur Fold/All-in (legalActions ["FOLD", "RAISE"]). + * Ende zu Ende mit dem Kern: Lobbyzeilen aus dem Bestand (turnier-bubble: 15 im Feld, 14 bezahlt), + dieselbe Hand ohne Lobby: im Turnier callt der BB den Shove mit weniger Händen als im Cash. + + python3 tests/turnier_anfrage_spec.py -v +""" +import json +import os +import sys +import unittest + +_w = os.path.dirname(os.path.abspath(__file__)) +while _w != "/" and not os.path.isdir(os.path.join(_w, "lesen")): + _w = os.path.dirname(_w) +for _u in ("lesen", "entscheiden", "hand", "client"): + sys.path.insert(0, os.path.join(_w, _u)) + +import decide +import spot_from_log + +LOBBY = "Comm_Tournament_117632" +TISCH = "₮1.10 6-Max Hyper 117632 Tisch 3" +HAND = "11763200019" +HELD = "Williamson1986" # 20205.88 Chips in der Rangliste +with open(os.path.join(_w, "archiv", "mitschrieb", "beispiele", "turnier-bubble.txt"), encoding="utf-8") as _f: + BUBBLE = _f.read() # Lobbyzeilen: Level 19 (1250/2500/312), 15 im Feld, 14 bezahlt +PREISE = [27.76, 18.28, 12.22, 8.38, 5.96, 4.45, 3.49, 2.89, 2.89, 2.48, 2.48, 2.19, 2.19, 2.19] +FELD_OHNE_UNS = [181821.41, 62866.91, 47562.93, 42266.69, 41797.34, 41582.58, 31898.98, 30676.8, + 30466.03, 27140.76, 25802.0, 24046.68, 22206.0, 20330.29, 14328.72] + + +def zeile(cmd, daten, raum=TISCH): + daten = dict(daten, gameHandId=daten.get("gameHandId", HAND)) + bohne = json.dumps(json.dumps(daten, separators=(",", ":")))[1:-1] + return ('2026-10-28 12:00:00:000 [info] [UNITY] Stdout: [Method] -> SendMessageToPipe - ' + '{"EventName":"extension_event","RequestId":null,"Data":{"cmd_bean":{"BeanData":"' + + bohne + f'","Cmd":"{cmd}","RoomName":"{raum}"}},"room_name":"{raum}"}}}}\n') + + +def karte(wert, farbe): + return {"suit": farbe, "value": wert} + + +def alldata(lobby=LOBBY, nummer=117632, game_type="Tournament"): + sitze = [{"seatId": 3, "userName": HELD, "userChips": 20205.88, "isPlaying": True}, + {"seatId": 2, "userName": "Leander77", "userChips": 20330.29, "isPlaying": True}, + {"seatId": 1, "userName": "QaQom", "userChips": 42266.69, "isPlaying": True}] + return zeile("game.game_alldata", { + "gameInitResponseData": {"bigBlind": 2500.0, "dealerSeatId": 1, "gameHandId": None}, + "seatInfoRsponseData": {"isGameStarted": False, "seatResponseDataList": sitze}, + "roomProperties": {"gameType": game_type, "miniGameTypeId": 1, "tournamentType": "TOURNAMENT"}, + "tourneyTableProperties": {"tournamentId": nummer, "tourneyLobbyName": lobby}}) + + +def alldata_ohne_lobby(): + """game_alldata mit gameType 'Tournament', aber OHNE tourneyTableProperties: die Beitritts-Zeile + ist aus dem 4-MB-Tail gescrollt, self.lobby bleibt None. Die Uebersetzung muss TROTZDEM greifen - + sonst setzt die Engine aus und der Laeufer foldet/checkt blind (Owner 9.11.: JJ pot-committed weg).""" + sitze = [{"seatId": 3, "userName": HELD, "userChips": 20205.88, "isPlaying": True}, + {"seatId": 2, "userName": "Leander77", "userChips": 20330.29, "isPlaying": True}, + {"seatId": 1, "userName": "QaQom", "userChips": 42266.69, "isPlaying": True}] + return zeile("game.game_alldata", { + "gameInitResponseData": {"bigBlind": 2500.0, "dealerSeatId": 1, "gameHandId": None}, + "seatInfoRsponseData": {"isGameStarted": False, "seatResponseDataList": sitze}, + "roomProperties": {"gameType": "Tournament", "miniGameTypeId": 1, "tournamentType": "TOURNAMENT"}}) + + +def hand(loch=(karte("ACE", "SPADES"), karte("NINE", "HEARTS")), gameHandId=HAND): + """Antes, SB 1250, BB 2500 (wir), Knopf foldet, SB schiebt 20018.29 (alles), wir am Zug.""" + h = {"gameHandId": gameHandId} + text = zeile("game.pre_hand_start_info", dict(h, dealerSeatId=1, bbAmount=2500.0, sbAmount=1250.0, + anteAmount=312.0)) + for sitz, name, nach in ((3, HELD, 19893.88), (2, "Leander77", 20018.29), (1, "QaQom", 41954.69)): + text += zeile("game.seat", dict(h, seatId=sitz, userName=name, caption="Ante", betAmout=312.0, + userChips=nach)) + text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="SB", betAmout=1250.0, + userChips=18768.29)) + text += zeile("game.seat", dict(h, seatId=3, userName=HELD, caption="BB", betAmout=2500.0, + userChips=17393.88)) + text += zeile("game.seat", dict(h, seatId=1, userName="QaQom", caption="Fold", betAmout=0.0, + userChips=41954.69)) + text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="AllIn", betAmout=20018.29, + userChips=0.0)) + text += zeile("game.hole_cards", dict(h, holeCards=list(loch))) + return text + + +def zug(gameHandId=HAND): + return zeile("game.user_turn", { + "gameHandId": gameHandId, "userTurnOptions": {"3": [], "4": [17393.88], "6": [], "5": [], "7": None}, + "whoseTurn": HELD, "turnTime": 16, "callAmount": 17393.88, "totalPot": 23454.29, + "extraTurnTime": 0, "extraTimerEnabled": False, "kpokerActions": None}) + + +def anfragen(text): + return [json.loads(z) for z, _, _, _, _ in spot_from_log.spots(text)] + + +class Lage(unittest.TestCase): + def setUp(self): + self.a, = anfragen(alldata() + BUBBLE + hand() + zug()) + + def test_preise_nach_rang(self): + self.assertEqual(self.a["tournament"]["payouts"], PREISE) + + def test_stapel_wir_zuerst_bei_handbeginn(self): + t = self.a["tournament"] + self.assertEqual(t["heroIndex"], 0) + self.assertAlmostEqual(t["stacks"][0], 17393.88 + 312 + 2500, places=2) # = 20205.88 + self.assertEqual(sorted(t["stacks"][1:], reverse=True), FELD_OHNE_UNS) # Rangliste ohne uns, ohne 0-Chips + + def test_level_und_ante(self): + self.assertEqual((self.a["tournament"]["level"], self.a["tournament"]["ante"]), (19, 312)) + + def test_spielt_normal(self): + self.assertEqual(self.a["variant"], "NLHE") + self.assertEqual(self.a["legalActions"], ["FOLD", "CALL"]) + self.assertNotIn("_unklar", self.a) + self.assertEqual(self.a["_turnier"], "ICM") + + +class Zuordnung(unittest.TestCase): + def test_ueber_die_turniernummer(self): + a, = anfragen(alldata(lobby=None) + BUBBLE + hand() + zug()) + self.assertEqual(a["tournament"]["payouts"], PREISE) + + def test_fremde_lobby_gehoert_nicht_zum_tisch(self): + a, = anfragen(alldata(lobby="Comm_Tournament_999", nummer=999) + BUBBLE + hand() + zug()) + self.assertNotIn("tournament", a) + self.assertEqual(a["legalActions"], ["FOLD", "CALL"]) # Chip-EV, nicht aussetzen + self.assertNotIn("_unklar", a) + self.assertEqual(a["_turnier"], "Chip-EV-Rückfall: Turnier: Preisliste fehlt") + + def test_cash_tisch_bleibt_cash(self): + a, = anfragen(alldata(lobby=None, nummer=0, game_type="Ring") + BUBBLE + hand() + zug()) + self.assertNotIn("tournament", a) + self.assertEqual(a["legalActions"], ["FOLD", "CALL"]) + self.assertNotIn("_turnier", a) + + def test_allinfold_ist_die_basisart_mit_fold_allin(self): + a, = anfragen(alldata(game_type="Allinfold") + BUBBLE + hand() + zug()) + self.assertEqual(a["variant"], "NLHE") + self.assertEqual(a["legalActions"], ["FOLD", "RAISE"]) + self.assertNotIn("_unklar", a) + + +class Reihenfolge(unittest.TestCase): + def test_meldungen_nach_dem_zug_zaehlen_nicht(self): + a, b = anfragen(alldata() + hand() + zug() + BUBBLE + hand(gameHandId="11763200020") + + zug(gameHandId="11763200020")) + self.assertEqual(a["legalActions"], ["FOLD", "CALL"]) + self.assertNotIn("tournament", a) + self.assertEqual(a["_turnier"], "Chip-EV-Rückfall: Turnier: Preisliste fehlt") + self.assertEqual(b["tournament"]["payouts"], PREISE) + + def test_ohne_rangliste_chip_ev(self): + ohne = "".join(z for z in BUBBLE.splitlines(True) if "tournamentlobby.rank_list" not in z) + a, = anfragen(alldata() + ohne + hand() + zug()) + self.assertEqual(a["legalActions"], ["FOLD", "CALL"]) + self.assertNotIn("tournament", a) + self.assertEqual(a["_turnier"], "Chip-EV-Rückfall: Turnier: Rangliste fehlt") + + +def tischrahmen(text=BUBBLE, raum=TISCH): + """Dieselben vier Lobby-Meldungen, aber als Rahmen auf dem TISCHkanal (cmd_bean.Cmd tournamentlobby.*).""" + import turnier + aus = "" + for _, _, art, d in turnier.meldungen(text): + cmd = {v: k for k, v in turnier.ARTEN.items()}[art] + bohne = json.dumps(json.dumps(d, separators=(",", ":")))[1:-1] + aus += ('2026-11-04 12:00:00:000 [info] [UNITY] Stdout: [Method] -> SendMessageToPipe - ' + '{"EventName":"extension_event","RequestId":null,"Data":{"cmd_bean":{"BeanData":"' + + bohne + f'","Cmd":"{cmd}","RoomName":"{raum}"}},"room_name":"{raum}"}}}}\n') + return aus + + +class Tischkanal(unittest.TestCase): + """Die Lobby auf dem Tischkanal (gemessen 04.11.: 11x tournamentlobby.dynamic_lobby_data am Tisch).""" + + def test_rahmen_am_tisch_geben_die_lage(self): + a, = anfragen(alldata() + tischrahmen() + hand() + zug()) + self.assertEqual(a["tournament"]["payouts"], PREISE) + self.assertEqual((a["tournament"]["level"], a["tournament"]["ante"]), (19, 312)) + self.assertEqual(a["_turnier"], "ICM") + + def test_rahmen_machen_den_tisch_zum_turniertisch_auch_ohne_beitritt(self): + a, = anfragen(alldata_ohne_lobby() + tischrahmen() + hand() + zug()) + self.assertEqual(a["tournament"]["payouts"], PREISE) + + def test_rahmen_eines_anderen_tisches_zaehlen_nicht(self): + a, = anfragen(alldata() + tischrahmen(raum="anderer Tisch 9") + hand() + zug()) + self.assertNotIn("tournament", a) + self.assertEqual(a["_turnier"], "Chip-EV-Rückfall: Turnier: Preisliste fehlt") + + +RANG = "AKQJT98765432" +NAME = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", "8": "EIGHT", + "7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"} + + +def haende(): + aus = [] + for i, a in enumerate(RANG): + for b in RANG[i:]: + zweite = "HEARTS" if a == b else "SPADES" + aus.append((karte(NAME[a], "SPADES"), karte(NAME[b], zweite))) + if a != b: + aus.append((karte(NAME[a], "SPADES"), karte(NAME[b], "HEARTS"))) + return aus + + +@unittest.skipUnless(decide.bereit(), "Kern nicht gebaut") +class EndeZuEnde(unittest.TestCase): + """Lobby (Bubble: 15 im Feld, 14 bezahlt), dieselbe Hand mit 169 Startkarten.""" + + def test_bubble_callt_enger_als_cash(self): + turnier, cash = [], [] + for n, loch in enumerate(haende()): + # Hand-IDs NACH der Beitrittszeile (alldata traegt HAND = ...0019): kleinere IDs sind fuer + # den Leser spaete Zeilen einer alten Hand - ohne Verlauf kein Angreifer, keine ICM-Praemie. + nr = f"1176321{n:04d}" + turnier.append(spot_from_log.spots(alldata() + BUBBLE + hand(loch, nr) + zug(nr))[0][0]) + cash.append(spot_from_log.spots(alldata(lobby=None, nummer=0, game_type="Ring") + + hand(loch, nr) + zug(nr))[0][0]) + self.assertTrue(all("tournament" in json.loads(z) for z in turnier)) + calls = [sum(a["action"] == "CALL" for a in decide.entscheide(z, timeout=300)) for z in (turnier, cash)] + print(f"\n8 BB im BB gegen Shove, 169 Hände: Turnier (Bubble) {calls[0]} Calls, Cash {calls[1]}") + self.assertLess(calls[0], calls[1]) + + +def zug_offen(gameHandId=HAND): + """Unser Zug am Turniertisch, nichts zu callen - mit dem ECHTEN Freeroll-Optionsformat + (live 9.11. gemessen): callAmount 0, "5" leer, "4" null, eigene Schluessel 7/8/9. Im Cash + stehen hier die Raise-Groessen in "5"; im Turnier nicht - der Parser fand darum nie ein RAISE.""" + return zeile("game.user_turn", { + "gameHandId": gameHandId, "whoseTurn": HELD, "turnTime": 16, "callAmount": 0.0, + "totalPot": 900.0, "extraTurnTime": 0, "extraTimerEnabled": False, "kpokerActions": None, + "userTurnOptions": {"3": [], "4": None, "6": [], "5": [], "7": [], "8": [], "9": []}}) + + +def hand_offen(loch=(karte("ACE", "SPADES"), karte("QUEEN", "HEARTS")), gameHandId=HAND): + """Wir sind BB mit Stapel, der SB limpt/ergaenzt - wir koennen checken ODER jammen (kein Shove gegen uns).""" + h = {"gameHandId": gameHandId} + text = zeile("game.pre_hand_start_info", dict(h, dealerSeatId=1, bbAmount=2500.0, sbAmount=1250.0)) + text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="SB", betAmout=1250.0, + userChips=18768.29)) + text += zeile("game.seat", dict(h, seatId=3, userName=HELD, caption="BB", betAmout=2500.0, + userChips=17393.88)) + text += zeile("game.seat", dict(h, seatId=2, userName="Leander77", caption="Call", betAmout=2500.0, + userChips=17518.29)) + text += zeile("game.hole_cards", dict(h, holeCards=list(loch))) + return text + + +class JamAmTurniertisch(unittest.TestCase): + """Am Turniertisch MUSS der Jam (All-in) verfuegbar sein: der Server listet die Raise-Groessen + nicht wie im Cash ("5" leer), sonst bekam der Bot nur Fold/Check und foldete/checkte JEDE Hand + (Owner 9.11.: 'er sitzt angemeldet, foldet aber alles; AQ -> Fold').""" + + def test_raise_als_jam_verfuegbar(self): + a, = anfragen(alldata_ohne_lobby() + hand_offen() + zug_offen()) + self.assertIn("RAISE", a["legalActions"]) + self.assertEqual(a["minRaiseTo"], a["heroStack"]) # Jam = All-in (ganzer Stapel) + self.assertEqual(a["maxRaiseTo"], a["heroStack"]) + + def test_cashtisch_bleibt_ohne_erfundenes_raise(self): + # derselbe leere Optionssatz an einem RING-Tisch: KEIN erfundenes RAISE (nur Turnier-Rueckfall) + a, = anfragen(alldata(lobby=None, nummer=0, game_type="Ring") + hand_offen() + zug_offen()) + self.assertNotIn("RAISE", a["legalActions"]) + + +class OhneBeitrittsZeile(unittest.TestCase): + """gameType 'Tournament', aber die Beitritts-Zeile (tourneyTableProperties) ist aus dem Tail + gescrollt - self.lobby None. Frueher setzte die Engine aus ('gameType Tournament nicht + abgebildet'), der Laeufer foldete/checkte blind (Owner 9.11.: JJ pot-committed weg, 180/910).""" + + def test_turniertisch_uebersetzt_auch_ohne_lobby(self): + a, = anfragen(alldata_ohne_lobby() + hand() + zug()) + self.assertEqual(a["variant"], "NLHE") # Turniertisch IST ein Pokertisch + self.assertTrue(a.get("legalActions")) # nicht leer = nicht ausgesetzt + self.assertNotIn("tournament", a) # ohne Lobby kein ICM-Feld - aber chip-EV spielt + self.assertEqual(a["_turnier"], "Chip-EV-Rückfall: Turnier: Lobby unbekannt") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/turnier_spots.py b/tests/turnier_spots.py new file mode 100644 index 00000000..928641e6 --- /dev/null +++ b/tests/turnier_spots.py @@ -0,0 +1,71 @@ +"""Turnier-Spots als Kern-Anfragen (Fixture-Bau fuer tests/turnier_spots_spec.py). + +Ein Spot ist ein Vorflop-Tisch mit Knopf, Blinds, Antes und dem Verlauf bis zu Heros Zug, eingebettet in +ein Turnierfeld (`tournament`: payouts, stacks bei Handbeginn, heroIndex 0). Betraege in Chips, BB = 100. +""" +import json + +RANG = {"A": "ACE", "K": "KING", "Q": "QUEEN", "J": "JACK", "T": "TEN", "9": "NINE", + "8": "EIGHT", "7": "SEVEN", "6": "SIX", "5": "FIVE", "4": "FOUR", "3": "THREE", "2": "TWO"} +BB = 100.0 + + +def karten(h): + r1, r2 = RANG[h[0]], RANG[h[1]] + if len(h) == 2: + return [{"rank": r1, "suit": "SPADES"}, {"rank": r2, "suit": "HEARTS"}] + zweite = "SPADES" if h[2] == "s" else "HEARTS" + return [{"rank": r1, "suit": "SPADES"}, {"rank": r2, "suit": zweite}] + + +def spot(hand, tisch, held, knopf, payouts, feld, ante=0.0, jam=None, turnier=True): + """`tisch`: {Sitz: Stapel bei Handbeginn in BB} (Sitze 1..n im Uhrzeigersinn), `held` unser Sitz, + `knopf` der Knopf. SB/BB sind die beiden Sitze nach dem Knopf. Alle vor Held folden; `jam` = Sitz, + der vor Held all-in geht (sonst ist Held first in). `feld`: die Stapel (BB) der Spieler AUSSER dem + Tisch. -> JSON-Zeile.""" + n = len(tisch) + nach = lambda s, k=1: (s - 1 + k) % n + 1 + sb, bb = (nach(knopf), nach(knopf, 2)) if n > 2 else (knopf, nach(knopf)) + chips = {s: st * BB for s, st in tisch.items()} + rein = {s: 0.0 for s in tisch} + verlauf = [] + if ante: + for s in tisch: + verlauf.append({"street": "PREFLOP", "seat": s, "action": "POST_ANTE", "amount": ante * BB}) + vorher_ante = dict.fromkeys(tisch, ante * BB if ante else 0.0) + for s, art, betrag in ((sb, "POST_SB", BB / 2), (bb, "POST_BB", BB)): + verlauf.append({"street": "PREFLOP", "seat": s, "action": art, "amount": betrag}) + rein[s] = betrag + # Zugfolge vorflop: ab dem Sitz nach dem BB + folge = [nach(bb, k) for k in range(1, n + 1)] + gefoldet = set() + for s in folge: + if s == held: + break + if s == jam: + rein[s] = chips[s] - vorher_ante[s] + verlauf.append({"street": "PREFLOP", "seat": s, "action": "ALL_IN", "amount": rein[s]}) + else: + verlauf.append({"street": "PREFLOP", "seat": s, "action": "FOLD"}) + gefoldet.add(s) + pot = sum(rein.values()) + sum(vorher_ante.values()) + hinter = lambda s: chips[s] - vorher_ante[s] - rein[s] + to_call = max(rein.values()) - rein[held] + stack = hinter(held) + anfrage = { + "variant": "NLHE", "bigBlind": BB, "seats": n, "heroSeat": held, "heroCards": karten(hand), + "board": {}, "street": "PREFLOP", "pot": round(pot, 2), "toCall": round(min(to_call, stack), 2), + "heroStack": round(stack, 2), + "legalActions": ["FOLD", "CALL", "RAISE"] if stack > to_call else ["FOLD", "CALL"], + "minRaiseTo": round(min(stack + rein[held], max(rein.values()) + BB), 2) if stack > to_call else None, + "maxRaiseTo": round(stack + rein[held], 2) if stack > to_call else None, + "villains": [{"seat": s, "stack": round(hinter(s), 2), "folded": s in gefoldet} + for s in sorted(tisch) if s != held], + "history": verlauf, + } + if turnier: + anfrage["tournament"] = { + "payouts": payouts, + "stacks": [tisch[held] * BB] + [tisch[s] * BB for s in sorted(tisch) if s != held] + [f * BB for f in feld], + "heroIndex": 0, "ante": ante * BB, "level": 12} + return json.dumps({k: v for k, v in anfrage.items() if v is not None}) diff --git a/tests/turnier_spots_spec.py b/tests/turnier_spots_spec.py new file mode 100644 index 00000000..9ccb5d82 --- /dev/null +++ b/tests/turnier_spots_spec.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Spezifikation: Turnier-Spots mit erwarteter Aktion (ICM-Push/Fold, src/icm/push_fold.rs). + +Jeder Spot ist eine echte Kern-Anfrage (tests/turnier_spots.py: Knopf, Blinds, Antes, Verlauf, Feld, +Preise) und wird zweimal gestellt: als Turnier (`tournament`) und als Cash (ohne). Erwartet wird die +Turnier-Aktion; wo ICM die Chip-Antwort umdreht, ist auch die Cash-Aktion festgehalten - das ist der +Beweis, dass die Turnierlage wirkt und Cash unberuehrt bleibt. + + Bubble (5 im Feld, 4 bezahlt, ein 2-BB-Zwerg): BB 10bb gegen SB-Jam - K8o foldet (Cash callt), + AJo callt weiter. + Kurzstack (7bb am Knopf, 56 im Feld, 9 bezahlt): K8o jammt, 72o foldet; K5o jammt NUR mit Antes + (die tote Ante weitet den Jam: Gleichgewicht 33 -> 41 %). + Finaltisch, Chipleader im SB gegen 6-BB-BB: 85o jammt (der Kurze muss eng callen), 72o foldet. + Finaltisch, 12bb am Knopf gegen Jam des Leaders KJo foldet (Cash callt), AQo callt. + (drei Spieler noch hinter dem Jam): + Rueckfall: unbepreisbare Lage (Stapel 0) -> decide.py fragt als Chip-EV nach, kein ABSTAIN, Grund + in `turnier`/`reason`. + + python3 tests/turnier_spots_spec.py -v +""" +import json +import os +import sys +import unittest + +_w = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(_w, "entscheiden")) +sys.path.insert(0, os.path.join(_w, "tests")) +import decide +import turnier_spots as T + +BUBBLE = dict(tisch={1: 30, 2: 10, 3: 10}, held=3, knopf=1, payouts=[50, 30, 15, 5], feld=[25, 2], jam=2) +KURZ = dict(tisch={1: 40, 2: 35, 3: 28, 4: 7, 5: 30, 6: 22}, held=4, knopf=4, + payouts=[30, 20, 14, 10, 8, 6, 5, 4, 3], feld=[30] * 50, ante=0.125) +FT_STEAL = dict(tisch={1: 50, 2: 6}, held=1, knopf=1, payouts=[35, 22, 15, 11, 9, 8], feld=[20, 18, 15, 12]) +FT_CALL = dict(tisch={1: 40, 2: 12, 3: 18, 4: 15, 5: 20, 6: 10}, held=2, knopf=2, + payouts=[35, 22, 15, 11, 9, 8], feld=[], jam=1, ante=0.125) + + +def aktion(hand, lage, turnier=True): + a, = decide.entscheide([T.spot(hand, **dict(lage, turnier=turnier))]) + return a["action"], a.get("reason", "") + + +@unittest.skipUnless(decide.bereit(), "Kern nicht gebaut") +class Spots(unittest.TestCase): + def pruefe(self, hand, lage, erwartet, cash=None): + got, grund = aktion(hand, lage) + self.assertEqual(got, erwartet, f"{hand}: {grund}") + self.assertIn("ICM push/fold", grund) + if cash is not None: + self.assertEqual(aktion(hand, lage, turnier=False)[0], cash, f"{hand} im Cash") + + def test_bubble_bb_foldet_k8o_gegen_den_sb_jam(self): + self.pruefe("K8o", BUBBLE, "FOLD", cash="CALL") + + def test_bubble_bb_callt_ajo_weiter(self): + self.pruefe("AJo", BUBBLE, "CALL", cash="CALL") + + def test_kurzstack_knopf_jammt_k8o(self): + self.pruefe("K8o", KURZ, "RAISE") + + def test_kurzstack_knopf_foldet_72o(self): + self.pruefe("72o", KURZ, "FOLD") + + def test_ante_weitet_den_jam(self): + self.pruefe("K5o", KURZ, "RAISE") + self.pruefe("K5o", dict(KURZ, ante=0.0), "FOLD") + + def test_finaltisch_leader_stiehlt_breit_gegen_den_kurzen(self): + self.pruefe("85o", FT_STEAL, "RAISE") + self.pruefe("72o", FT_STEAL, "FOLD", cash="RAISE") + + def test_finaltisch_foldet_kjo_gegen_den_leader(self): + self.pruefe("KJo", FT_CALL, "FOLD", cash="CALL") + + def test_finaltisch_callt_aqo_gegen_den_leader(self): + self.pruefe("AQo", FT_CALL, "CALL", cash="CALL") + + +@unittest.skipUnless(decide.bereit(), "Kern nicht gebaut") +class Rueckfall(unittest.TestCase): + def test_unbepreisbare_lage_spielt_chip_ev_mit_grund(self): + anfrage = json.loads(T.spot("AJo", **BUBBLE)) + anfrage["tournament"]["stacks"][2] = 0.0 # ein Stapel 0: der Kern kann nicht bepreisen + a, = decide.entscheide([json.dumps(anfrage)]) + self.assertNotEqual(a["action"], "ABSTAIN", a.get("reason")) + self.assertTrue(a["turnier"].startswith("Chip-EV-Rückfall: Kern: tournament situation"), a["turnier"]) + self.assertIn("| Turnier: Chip-EV-Rückfall", a["reason"]) + + def test_modus_steht_in_der_antwort(self): + anfrage = json.loads(T.spot("AJo", **BUBBLE)) + anfrage["_turnier"] = "ICM" + a, = decide.entscheide([json.dumps(anfrage)]) + self.assertEqual(a["turnier"], "ICM") + self.assertTrue(a["reason"].endswith("| Turnier: ICM"), a["reason"]) + + def test_cash_bleibt_unberuehrt(self): + z = T.spot("AJo", **dict(BUBBLE, turnier=False)) + a, = decide.entscheide([z]) + self.assertNotIn("turnier", a) + self.assertNotIn("Turnier", a["reason"]) + + +if __name__ == "__main__": + unittest.main()