From 6f16774b5d2958593768fa44678d58f1288bafc8 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Thu, 26 Nov 2026 17:12:18 +0100 Subject: [PATCH] Bounty/PKO/Mystery: Kopfgelder aus dem Client in die Anfrage, Turniermotor rechnet Rauswuerfe gedeckter Gegner in Geld Co-Authored-By: Claude Opus 5.5 --- entscheiden/turniermotor/src/turnier.rs | 74 +++++++++++++++++++++++-- lesen/spot_from_log.py | 39 +++++++++++++ lesen/turnier.py | 32 ++++++++++- messung/turnier/bounty_probe.py | 42 ++++++++++++++ tests/bounty_spec.py | 74 +++++++++++++++++++++++++ 5 files changed, 254 insertions(+), 7 deletions(-) create mode 100644 messung/turnier/bounty_probe.py create mode 100644 tests/bounty_spec.py diff --git a/entscheiden/turniermotor/src/turnier.rs b/entscheiden/turniermotor/src/turnier.rs index b9e8ade8..5b3b9e6c 100644 --- a/entscheiden/turniermotor/src/turnier.rs +++ b/entscheiden/turniermotor/src/turnier.rs @@ -80,6 +80,36 @@ fn bezahlt(q: &Value, s: i64) -> f64 { geld(true, "").iter().sum::() + ["PREFLOP", "FLOP", "TURN", "RIVER"].iter().map(|st| geld(false, st).into_iter().fold(0.0, f64::max)).sum::() } +/// Kopfgeld je Motorplatz (gleiche Zaehlung wie dienst::versuche: ab SB, die vorderen Plaetze fehlen bei +/// weniger Spielern) in heutigen Chips, nur fuer Gegner, die wir decken (sonst kann der Rauswurf nicht an +/// uns fallen). PKO: die Haelfte bar, die andere Haelfte auf den eigenen Kopf, die zaehlt halb. +pub fn kopfgelder(q: &Value, n: usize, g: &Geld, nur_allin: bool) -> [f64; MAXN] { + let mut aus = [0f64; MAXN]; + let b = &q["tournament"]["bounty"]; + if !b.is_object() || g.kurs <= 0.0 { + return aus; + } + let faktor = if b["art"] == "pko" { 0.75 } else { 1.0 }; + let held = q["heroSeat"].as_i64().unwrap_or(-1); + let mein = q["heroStack"].as_f64().unwrap_or(0.0) + bezahlt(q, held); + let p = plaetze(q); + let m = p.len(); + if m > n || m < 2 { + return aus; + } + for v in q["villains"].as_array().into_iter().flatten() { + let (s, k) = (sitz(v), v["bounty"].as_f64().unwrap_or(0.0)); + let start = v["stack"].as_f64().unwrap_or(0.0) + bezahlt(q, s); + if k <= 0.0 || start > mein + 1e-9 || v["folded"] == true || (nur_allin && v["stack"].as_f64().unwrap_or(1.0) > 1e-9) { + continue; + } + if let Some(j) = p.iter().position(|x| *x == s) { + aus[if j < 2 { j } else { n - m + j }] = k * faktor / g.kurs; + } + } + aus +} + /// Wirksame Tiefe der Hand in bb, Stapel zu Handbeginn: gegen den, der freiwillig gesetzt hat, sonst gegen den mittleren Gegner. fn tiefe(q: &Value) -> f64 { let bb = q["bigBlind"].as_f64().unwrap_or(1.0); @@ -109,6 +139,8 @@ pub struct Geld { h: Vec, w: Vec, pub jetzt: f64, + /// Geld je heutigem Chip (Steigung beim eigenen Stapel): rechnet Kopfgelder in Chips um + pub kurs: f64, } impl Geld { @@ -150,12 +182,13 @@ impl Geld { for i in 1..w.len() { w[i] = w[i].max(w[i - 1]); // mehr Chips sind nie weniger wert: Stichprobenrauschen glaetten } - let mut g = Geld { h, w, jetzt: hero }; + let mut g = Geld { h, w, jetzt: hero, kurs: 1.0 }; let steil = (g.von(hero) - g.von(hero * 0.75)) / (hero * 0.25); if steil <= 0.0 { return None; } g.w.iter_mut().for_each(|x| *x /= steil); // in heutigen Chips + g.kurs = steil; Some(g) } pub fn von(&self, x: f64) -> f64 { @@ -236,7 +269,8 @@ impl Motor { if l.fehler.is_some() || grund.contains(" genau (") || a["zug"].is_null() { // grosser Call: Gewinnchance gegen den Preis in Geld if a["action"] == "CALL" && offen >= 0.25 * rest { - let noetig = g.noetig(rest, offen.min(rest), pot); + let kopf: f64 = kopfgelder(q, self.s.n, g, true).iter().sum(); + let noetig = g.noetig(rest, offen.min(rest), pot + kopf); if let Some(eq) = self.gewinnchance(q, l, *ich, *hand, brett).filter(|eq| *eq < noetig) { a["reason"] = json!(format!("ICM: Gewinnchance {:.0}%, noetig {:.0}% -> fold; {grund}", eq * 100.0, noetig * 100.0)); a["action"] = json!("FOLD"); @@ -267,6 +301,8 @@ impl Motor { let mut rng = Rng(misch(hand.0 as u64 * 52 + hand.1 as u64, 4242) | 1); let enger = behaelt(g, self.s.stack as f64 / 100.0 * bb, (150.0 + self.s.splash as f64) / 100.0 * bb) as f32; let mut callt: std::collections::HashMap = Default::default(); + let kopf = kopfgelder(q, self.s.n, g, false); + let mit_kopf = kopf.iter().any(|x| *x > 0.0); // je Zug Summe in Geld; je Ziehung und Zug Geld minus Chips let mut summe = [0f64; MAXA]; let mut diff: Vec<[f32; MAXA]> = vec![]; @@ -343,7 +379,16 @@ impl Motor { let mut aus = [0f32; MAXN]; y.auszahlung(&self.s, &d.wert, &mut aus); let chips = aus[*ich as usize] as f64 * bb; - let geld = g.von((g.jetzt + chips).max(0.0)) - g.von(g.jetzt); + let mut geld = g.von((g.jetzt + chips).max(0.0)) - g.von(g.jetzt); + // Rauswurf eines gedeckten Gegners mit Kopfgeld: er hat alles verloren, wir haben gewonnen + if mit_kopf && aus[*ich as usize] > 0.0 { + for p in 0..self.s.n { + let rest = y.stack[p] as f32 + y.gesamt[p] as f32 + aus[p] * 100.0; + if kopf[p] > 0.0 && y.gesamt[p] > 0 && rest <= 0.5 { + geld += kopf[p]; + } + } + } summe[i] += geld; zeile[i] = ((geld - chips) / bb) as f32; } @@ -353,7 +398,8 @@ impl Motor { let (Some(w), true) = (a["zug"].as_u64().map(|x| x as usize), n >= 300.0) else { return a }; // Die Grundstrategie ist in Chips im Gleichgewicht: es zaehlt, was Geld gegenueber Chips verschiebt. // Wechseln nur auf Zuege, die sie spielt, oder auf Fold/Check. - let frei = |i: usize| i == w || v[i] >= 0.02 || menue.z[i].code == FOLD || (menue.z[i].code == CALL && offen <= 0.0); + // Mit Kopfgeld auch der Call: der Rauswurf ist Geld, das die Chip-Strategie nicht kennt. + let frei = |i: usize| i == w || v[i] >= 0.02 || menue.z[i].code == FOLD || (menue.z[i].code == CALL && (offen <= 0.0 || mit_kopf)); let mw = |i: usize| summe[i] / n / bb; let Some(best) = (0..menue.n).filter(|&i| frei(i)).max_by(|&i, &j| mw(i).total_cmp(&mw(j))) else { return a }; if best == w { @@ -367,7 +413,8 @@ impl Motor { return a; } let (akt, groesse) = self.zug_in_antwort(q, l, *ich, &menue, best, offen, pot); - a["reason"] = json!(format!("ICM: {} -> {akt} (+{vorteil:.2} bb in Geld); {grund}", a["action"].as_str().unwrap_or(""))); + let was = if mit_kopf { "ICM+Bounty" } else { "ICM" }; + a["reason"] = json!(format!("{was}: {} -> {akt} (+{vorteil:.2} bb in Geld); {grund}", a["action"].as_str().unwrap_or(""))); a["action"] = json!(akt); a["size"] = json!(groesse); a @@ -385,6 +432,23 @@ mod tests { assert!((g.noetig(1000.0, 1000.0, 1500.0) - 0.4).abs() < 0.04, "{}", g.noetig(1000.0, 1000.0, 1500.0)); } + #[test] + fn kopfgeld_nur_fuer_gedeckte() { + let g = Geld::aus(&[50.0, 30.0, 20.0], &[3000.0, 2000.0, 1000.0, 1000.0], 0, 1000.0).unwrap(); + let q = json!({"heroSeat": 10, "heroStack": 3000.0, "bigBlind": 100.0, + "tournament": {"bounty": {"art": "bounty", "heroBounty": 5.0}}, + "villains": [{"seat": 20, "stack": 2000.0, "bounty": 5.0}, {"seat": 30, "stack": 4000.0, "bounty": 5.0}], + "history": [{"street": "PREFLOP", "seat": 20, "action": "POST_SB", "amount": 0.0}, + {"street": "PREFLOP", "seat": 30, "action": "POST_BB", "amount": 0.0}]}); + let k = kopfgelder(&q, 8, &g, false); + assert!(kopfgelder(&q, 8, &g, true).iter().all(|x| *x == 0.0)); // keiner all-in + // Plaetze ab SB: 20 (0), 30 (1), 10 (letzter); 30 deckt uns -> kein Kopfgeld + assert!(k[0] > 0.0 && (k[0] - 5.0 / g.kurs).abs() < 1e-9); + assert_eq!(k[1], 0.0); + let ohne = json!({"heroSeat": 10, "heroStack": 3000.0, "villains": [{"seat": 20, "stack": 2000.0, "bounty": 5.0}]}); + assert!(kopfgelder(&ohne, 8, &g, false).iter().all(|x| *x == 0.0)); + } + #[test] fn bubble_verlangt_mehr() { let g = Geld::aus(&[50.0, 30.0, 20.0], &[1000.0; 4], 0, 1500.0).unwrap(); diff --git a/lesen/spot_from_log.py b/lesen/spot_from_log.py index b7168a69..8a9cea36 100644 --- a/lesen/spot_from_log.py +++ b/lesen/spot_from_log.py @@ -357,6 +357,8 @@ class Tisch: self.verlauf = [] self.bb = None self.spielt = {} # Sitz -> isPlaying aus der letzten Sitzliste + self.kopfgeld = {} # Name -> Kopfgeld (selfBountyAmt der Sitzliste, bountyOnHead nach einem Rauswurf) + self.bounty = None # tourneyTableProperties.isBountyTournament (None = nicht gesagt) self.letzter_zug = None # (Hand, Straße, Call, Topf) des letzten eigenen Zugs self.art = None # Spielart des Tisches (bleibt über Hände), siehe `spielart` self.rueckgaben = set() # schon verbuchte return_chips der laufenden Hand (dieselbe Zeile kann doppelt stehen) @@ -374,11 +376,28 @@ class Tisch: `Comm_Tournament_` (tournamentId > 0). Im Cash ist die Nummer 0 und der Name null.""" tp = d.get("tourneyTableProperties") or {} nummer = tp.get("tournamentId") + if isinstance(tp.get("isBountyTournament"), bool): + self.bounty = tp["isBountyTournament"] if tp.get("tourneyLobbyName"): self.lobby = tp["tourneyLobbyName"] elif isinstance(nummer, int) and not isinstance(nummer, bool) and nummer > 0: self.lobby = f"Comm_Tournament_{nummer}" + def merke_kopfgeld(self, name, betrag): + """Kopfgeld eines Spielers: Zahl, oder ein Objekt mit einer Zahl (`bountyOnHead` ist im Client ein + Objekt, Form ungemessen: amount/value/bountyAmount/total). 0 oder fehlend: nichts.""" + if isinstance(betrag, dict): + betrag = next((betrag[k] for k in ("amount", "bountyAmount", "value", "total", "bounty") + if isinstance(betrag.get(k), (int, float)) and not isinstance(betrag.get(k), bool)), None) + if name and isinstance(betrag, (int, float)) and not isinstance(betrag, bool) and betrag > 0: + self.kopfgeld[name] = float(betrag) + + def kopfgelder(self, sitze): + """Sitz -> Kopfgeld fuer die Anfrage; leer ausserhalb von Bounty-Turnieren.""" + if self.bounty is False: + return {} + return {s: self.kopfgeld[self.namen[s]] for s in sitze if self.namen.get(s) in self.kopfgeld} + def merke_splash(self, betrag, hand=None): """Ein Splash-Betrag aus `game.splash_the_pot.dropAmount` oder `game.potInfo.splashPotDropAmount` (Chips); 0.0/None ist die Animation ohne Geld und zaehlt nicht.""" @@ -813,6 +832,14 @@ class Tisch: profile = self.profile # die Zaehlung darf eine Anfrage nie reissen if _gegnerzahl_fest(): draussen = draussen | self.gefoldet | self.nie_dran(plan, held_seat, strasse, turn.get("totalPot")) + kopf = self.kopfgelder(plan) if feld else {} + if feld and not kopf and self.bounty is not False and feld.get("mysteryBounty"): + # Mystery: der Umschlag ist verdeckt, jeder Rauswurf ist im Mittel so viel wert + kopf = {s: feld["mysteryBounty"] for s in plan} + if kopf and feld: + feld = dict(feld, bounty={"heroBounty": kopf.get(held_seat, 0.0), + "art": "mystery" if feld.get("mysteryBounty") and not self.kopfgelder(plan) + else "pko" if self.bounty else "bounty"}) gegner = [{"seat": plan[s], "stack": self.chips.get(s, bb * 50), "folded": self.aktion.get(s) == "Fold" or self.status.get(s) in DRAUSSEN or s in draussen, # Marke des Clients (lesen/tags.py): kostenlose Einordnung, geht als Feld mit @@ -821,6 +848,8 @@ class Tisch: # Nutzerkennung (Sitzliste): Schluessel des Gegner-Gedaechtnisses (lesen/uebergabe.py, entscheiden/decide.py). # Der Kern ueberliest das Feld (Draht liest Felder einzeln), die Anfrage bleibt fuer ihn bitgleich. **({"kennung": self.kennung[s]} if self.kennung.get(s) is not None else {}), + # Kopfgeld (Bounty-Turnier): der Turniermotor rechnet den Rauswurf in Geld mit + **({"bounty": kopf[s]} if s in kopf else {}), # Spieler-Vorwissen (Schalter VORWISSEN, lesen/vorwissen): gesalzener Hash des Anzeigenamens; aus = kein Feld. **_vw_feld(self.namen.get(s))} for s in sorted(plan) if s != held_seat] @@ -1157,6 +1186,7 @@ class Leser: if s.get("seatId") is not None and s.get("userName"): t.namen[s["seatId"]] = s["userName"] t.chips[s["seatId"]] = s.get("userChips", 0) + t.merke_kopfgeld(s["userName"], s.get("selfBountyAmt")) if (d.get("seatInfoRsponseData") or {}).get("isGameStarted") and s.get("isPlaying") is False: t.aktion[s["seatId"]] = "Fold" # nicht in der Hand t.gefoldet.add(s["seatId"]) @@ -1171,6 +1201,7 @@ class Leser: if s.get("seatId") is not None and s.get("userName"): t.namen[s["seatId"]] = s["userName"] t.chips[s["seatId"]] = s.get("userChips", t.chips.get(s["seatId"], 0)) + t.merke_kopfgeld(s["userName"], s.get("selfBountyAmt")) if s.get("caption"): t.status[s["seatId"]] = s["caption"] if isinstance(s.get("isPlaying"), bool): @@ -1181,6 +1212,7 @@ class Leser: t.neuer_hand(d.get("gameHandId")) t.namen[sid] = d["userName"] t.chips[sid] = d.get("userChips", t.chips.get(sid, 0)) + t.merke_kopfgeld(d["userName"], d.get("selfBountyAmt")) if d.get("gameHandId") in (None, t.hand): t.sitz(d) elif cmd == "game.reveal_cards": @@ -1217,6 +1249,13 @@ class Leser: t.neuer_hand(d.get("gameHandId")) if d.get("gameHandId") == t.hand: t.zurueck(d) + elif cmd == "game.bounty_winnings_data": + # BountyWinnerBean: bountyWinnerData = [PlayerBountyInfoBean{playerName, seatId, bountyOnHead}] + t.bounty = True if t.bounty is None else t.bounty + for e in d.get("bountyWinnerData") or []: + if isinstance(e, dict): + name = e.get("playerName") or t.namen.get(e.get("seatId")) + t.merke_kopfgeld(name, e.get("bountyOnHead")) elif cmd == "game.hole_cards": self._karten_merken(d.get("gameHandId"), d.get("holeCards")) elif cmd == "game.player_info": diff --git a/lesen/turnier.py b/lesen/turnier.py index dea0e0d1..6ccb9ece 100644 --- a/lesen/turnier.py +++ b/lesen/turnier.py @@ -86,7 +86,11 @@ MARKE = '"EventName":"receive_from_tournament_lobby"' ARTEN = {"tournamentlobby.dynamic_lobby_data": "dyn", "tournamentlobby.user_dynamic_lobby_data": "user", "tournamentlobby.prize_list": "preise", - "tournamentlobby.rank_list": "rang"} + "tournamentlobby.rank_list": "rang", + # Mystery-Bounty-Verteilung (MysteryBountyDistributionBean, app.asar-Menue mystery_bounty_details); + # im Archiv noch nie gesehen - Name nach dem Muster der anderen, Felder aus dem Client-IL. + "tournamentlobby.mystery_bounty_details": "mystery", + "tournamentlobby.mystery_bounty_distribution": "mystery"} # Ein langer String wird im Log mitten im Wert umgebrochen; der Umbruch kann zwischen `\` und `"` # fallen (dann endet ein naives [^"\\]-Muster zu frueh: 17 der 210 Ranglisten gingen verloren). @@ -287,9 +291,33 @@ def kern_feld(stand, held, start): return None, "Turnier: eigener Stapel unbekannt" feld = [e["chips"] for e in liste if isinstance(e, dict) and e.get("playerName") != held and _zahl(e.get("chips")) is not None and e["chips"] > 0] + mystery = mystery_schnitt(stand.get("mystery")) if stand.get("mystery") else None return {"payouts": [preise[r]["betrag"] for r in range(1, len(preise) + 1)], "stacks": [round(start, 2)] + feld, "heroIndex": 0, - "ante": _zahl(jetzt["ante"]) or 0, "level": jetzt["level"]}, None + "ante": _zahl(jetzt["ante"]) or 0, "level": jetzt["level"], + **({"mysteryBounty": mystery} if mystery else {})}, None + + +def mystery_schnitt(d): + """Mittlerer Umschlag einer Mystery-Bounty-Verteilung: MysteryBountyLevelData `amountPerBounty`, gewichtet + mit der Zahl je Stufe, wenn eine genannt ist (Feldname ungemessen). Keine Zahl -> None.""" + stufen = [] + + def suche(x): + if isinstance(x, dict): + if _zahl(x.get("amountPerBounty")) is not None: + n = next((x[k] for k in ("remainingBounties", "noOfBounties", "bountyCount", "count", "totalBounties") + if _zahl(x.get(k)) is not None), 1) + stufen.append((float(x["amountPerBounty"]), max(float(n), 0.0))) + else: + for v in x.values(): + suche(v) + elif isinstance(x, list): + for v in x: + suche(v) + suche(d) + zahl = sum(n for _, n in stufen) + return round(sum(a * n for a, n in stufen) / zahl, 6) if zahl > 0 else None # Die Felder, die ein ICM braucht (alles ausser Zusatzwissen wie Namen und Zeit) diff --git a/messung/turnier/bounty_probe.py b/messung/turnier/bounty_probe.py new file mode 100644 index 00000000..1a8f7710 --- /dev/null +++ b/messung/turnier/bounty_probe.py @@ -0,0 +1,42 @@ +"""Turniermotor: wirkt das Kopfgeld? BB gegen einen SB-Jam, je Hand mit und ohne Bounty (gedeckter Gegner). +python bounty_probe.py [exe] (Vorgabe: die Probe-Kopie pokerbench-turnier-bounty.exe)""" +import json, subprocess, sys, os +sys.stdout.reconfigure(encoding="utf-8") +O = r"C:\Users\marcm\pokerfreak-turniermotor" +EXE = sys.argv[1] if len(sys.argv) > 1 else O + r"\pokerbench-turnier-bounty.exe" +P = subprocess.Popen([EXE, "dienst", O + r"\klassen", O + r"\daten"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + text=True, encoding="utf-8", env={**os.environ, "RAYON_NUM_THREADS": "8"}) +NAME = dict(zip("AKQJT98765432", "ACE KING QUEEN JACK TEN NINE EIGHT SEVEN SIX FIVE FOUR THREE TWO".split())) + + +def frag(q): + P.stdin.write(json.dumps(q) + "\n"); P.stdin.flush() + return json.loads(P.stdout.readline()) + + +def lage(k, kopf, art="bounty"): + """6 Spieler, 20 bb Tiefe, 3 bezahlt von 6; SB jammt 10 bb, wir BB mit 20 bb, die anderen gefoldet.""" + s = ("SPADES", "SPADES") if k.endswith("s") else ("SPADES", "HEARTS") + hist = [{"street": "PREFLOP", "seat": 1, "action": "POST_SB", "amount": 50.0}, + {"street": "PREFLOP", "seat": 2, "action": "POST_BB", "amount": 100.0}] + hist += [{"street": "PREFLOP", "seat": x, "action": "FOLD", "amount": 0.0} for x in (3, 4, 5, 6)] + hist += [{"street": "PREFLOP", "seat": 1, "action": "ALL_IN", "amount": 1000.0}] + v = [{"seat": 1, "stack": 0.0, "folded": False}] + [{"seat": x, "stack": 2000.0, "folded": True} for x in (3, 4, 5, 6)] + t = {"payouts": [50.0, 30.0, 20.0], "stacks": [2000.0, 1000.0, 2000.0, 2000.0, 2000.0, 2000.0], "heroIndex": 0} + if kopf: + v[0]["bounty"] = kopf + t["bounty"] = {"art": art, "heroBounty": kopf} + return {"variant": "NLHE", "bigBlind": 100.0, "seats": 6, "heroSeat": 2, "buttonSeat": 6, "street": "PREFLOP", + "heroCards": [{"rank": NAME[k[0]], "suit": s[0]}, {"rank": NAME[k[1]], "suit": s[1]}], + "pot": 1100.0, "toCall": 900.0, "heroStack": 1900.0, "legalActions": ["FOLD", "CALL", "RAISE"], + "minRaiseTo": 2000.0, "maxRaiseTo": 2000.0, "villains": v, "history": hist, "tournament": t, "_turnier": "ICM"} + + +frag(lage("AA", 0)) # Laden +anders = 0 +for k in ["K2o", "Q5o", "J7o", "T8o", "96s", "75s", "A2o", "K7o", "Q9o", "J4s", "84s", "53s", "T2s"]: + a, b, c = (frag(lage(k, x, art))["action"] for x, art in ((0, "bounty"), (1.0, "bounty"), (1.0, "pko"))) + anders += a != b + print(f"{k:4} ohne {a:5} mit Bounty 1 {b:5} PKO {c:5}") +print("anders:", anders) +P.stdin.close() diff --git a/tests/bounty_spec.py b/tests/bounty_spec.py new file mode 100644 index 00000000..7700434a --- /dev/null +++ b/tests/bounty_spec.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Bounty-Turniere: Kopfgelder aus dem Client in die Anfrage (Owner 26.11. "pko usw"). + +Quellen (archiv/mitschrieb/SPECIALFAELLE.md, Client-IL): `tourneyTableProperties.isBountyTournament`, +je Sitz `selfBountyAmt` in der Sitzliste, nach einem Rauswurf `game.bounty_winnings_data` +(`bountyWinnerData` = [PlayerBountyInfoBean{playerName, seatId, bountyOnHead}]); Mystery-Verteilung +(`amountPerBounty`) ueber den Lobby-Kanal. Ein echter Bounty-Rahmen steht noch nicht im Archiv - die +Formen sind aus dem Client-Code, nicht gemessen. Der Motor (entscheiden/turniermotor/src/turnier.rs, +`kopfgelder`) rechnet den Rauswurf gedeckter Gegner in Geld; Probe: messung/turnier/bounty_probe.py. + + python tests/bounty_spec.py -v +""" +import json +import os +import sys +import unittest + +_W = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _p in ("betrieb", "lesen", "hand", "client", "entscheiden"): + sys.path.insert(0, os.path.join(_W, _p)) + +import spot_from_log # noqa: E402 +import turnier # noqa: E402 + + +def bohne(cmd, d, raum="PKO 1"): + inner = json.dumps(json.dumps(d))[1:-1] + return ('[Method] -> SendMessageToPipe - {"EventName":"extension_event","RequestId":null,"Data":{"cmd_bean":' + '{"BeanData":"%s","Cmd":"%s","RoomName":"%s"},"room_name":"%s"}}\n' % (inner, cmd, raum, raum)) + + +class Tisch(unittest.TestCase): + def test_kopfgeld_aus_zahl_und_objekt(self): + t = spot_from_log.Tisch("x") + t.namen = {1: "a", 2: "b", 3: "c"} + t.merke_kopfgeld("a", 2.5) + t.merke_kopfgeld("b", {"amount": 4.0}) + t.merke_kopfgeld("c", 0.0) + self.assertEqual(t.kopfgelder([1, 2, 3]), {1: 2.5, 2: 4.0}) + + def test_kein_bounty_turnier_kein_kopfgeld(self): + t = spot_from_log.Tisch("x") + t.namen = {1: "a"} + t.merke_kopfgeld("a", 2.5) + t.merke_turnier({"tourneyTableProperties": {"tournamentId": 7, "isBountyTournament": False}}) + self.assertEqual(t.kopfgelder([1]), {}) + + def test_rauswurf_rahmen_setzt_neues_kopfgeld(self): + text = bohne("game.seatInfo", {"seatResponseDataList": [ + {"seatId": 1, "userName": "a", "userChips": 900.0, "selfBountyAmt": 1.0}, + {"seatId": 2, "userName": "b", "userChips": 0.0, "selfBountyAmt": 1.0}]}) + text += bohne("game.bounty_winnings_data", {"bountyWinnerData": [ + {"playerId": 5, "playerName": "a", "seatId": 1, "bountyOnHead": 1.5, "bountyInWallet": 0.5}], + "mysteryBountyWinnerData": None}) + leser = spot_from_log.Leser() + leser.lesen(text, ende=True) + t = leser.tische["PKO 1"] + self.assertTrue(t.bounty) + self.assertEqual(t.kopfgeld, {"a": 1.5, "b": 1.0}) + + +class Mystery(unittest.TestCase): + def test_schnitt_gewichtet(self): + d = {"levels": [{"amountPerBounty": 10.0, "remainingBounties": 3}, + {"amountPerBounty": 100.0, "remainingBounties": 1}]} + self.assertAlmostEqual(turnier.mystery_schnitt(d), 32.5) + + def test_ohne_zahl_ungewichtet_und_leer(self): + self.assertAlmostEqual(turnier.mystery_schnitt([{"amountPerBounty": 2.0}, {"amountPerBounty": 4.0}]), 3.0) + self.assertIsNone(turnier.mystery_schnitt({"x": 1})) + + +if __name__ == "__main__": + unittest.main()