From a8d04dd4f364dfa661a8f8d23f3b76cc7cf8393f Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 14:36:47 +0100 Subject: [PATCH] Gegnerstatistiken des Clients als Profil in die Anfrage (10 Pruefungen) --- lesen/profil.py | 132 +++++++++++++++++++++++++++++++++++++++++ lesen/spot_from_log.py | 8 ++- tests/profil_spec.py | 98 ++++++++++++++++++++++++++++++ 3 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 lesen/profil.py create mode 100644 tests/profil_spec.py diff --git a/lesen/profil.py b/lesen/profil.py new file mode 100644 index 0000000..940247c --- /dev/null +++ b/lesen/profil.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Gegnerprofile aus den Statistiken des Clients. + +Der Client holt die Werte selbst: `hud_stats` liefert je Nutzerkennung Zahlen in +Prozent. Die Sitzliste führt Sitz, Name und Kennung zusammen. Daraus entsteht ein +Profil je Sitz - das ist die Grundlage dafür, dass der Kern ausnutzen kann. + +Ehrlich zur Herkunft von `foldToBet`: Der Client kennt kein Feld dieses Namens. +Genommen wird `fta` (fold to aggression), weil Aufgeben gegen Druck genau das ist, +was der Erwartungswert eines Einsatzes braucht. Fehlt es, dient das gesamte +Folden als Ersatz. Beides wird als Schätzung behandelt, nicht als Wahrheit. + + from profil import profile_je_sitz +""" +import json +import re + +FELDER = {"vpip": "vpip", "pfr": "pfr"} +FALTEN = ("fta", "fold") +STATISTIK = re.compile(r'"api"\s*:\s*"hud_stats"') + + +def _klar(text): + """Der Client schreibt die Nutzlast maskiert - zurück in lesbare Form.""" + return text.replace('\\"', '"') + + +def _objekt(text, ab): + """Liest ein JSON-Objekt ab `ab` (zeigt auf '{') klammergerecht aus.""" + tiefe = 0 + im_text = False + schutz = False + for i in range(ab, len(text)): + z = text[i] + if im_text: + if schutz: + schutz = False + elif z == "\\": + schutz = True + elif z == '"': + im_text = False + elif z == '"': + im_text = True + elif z == "{": + tiefe += 1 + elif z == "}": + tiefe -= 1 + if tiefe == 0: + return text[ab:i + 1] + return None + + +def _anteil(wert): + try: + return min(max(float(wert) / 100.0, 0.0), 1.0) + except (TypeError, ValueError): + return None + + +def statistiken(text): + """{kennung: {"vpip": 0..1, "pfr": 0..1, "foldToBet": 0..1}} - spätere Angaben gewinnen.""" + klar = _klar(text) + ergebnis = {} + for treffer in STATISTIK.finditer(klar): + stelle = klar.find('"msg"', treffer.end()) + if stelle < 0: + continue + klammer = klar.find("{", stelle) + roh = _objekt(klar, klammer) if klammer > 0 else None + if not roh: + continue + try: + inhalte = json.loads(roh) + except ValueError: + continue + for kennung, eintrag in inhalte.items(): + if not isinstance(eintrag, dict): + continue + werte = next((w for w in eintrag.values() if isinstance(w, dict)), None) + if not werte: + continue + profil_werte = {} + for ziel, quelle in FELDER.items(): + anteil = _anteil(werte.get(quelle)) + if anteil is not None: + profil_werte[ziel] = anteil + for quelle in FALTEN: + if quelle in werte: + anteil = _anteil(werte.get(quelle)) + if anteil is not None: + profil_werte["foldToBet"] = anteil + break + if profil_werte: + ergebnis[str(kennung)] = profil_werte + return ergebnis + + +def sitze(text): + """{sitz: kennung} aus der Sitzliste.""" + klar = _klar(text) + ergebnis = {} + stelle = klar.find('"seatResponseDataList"') + while stelle >= 0: + klammer = klar.find("[", stelle) + if klammer < 0: + break + tiefe = 0 + for i in range(klammer, len(klar)): + if klar[i] == "[": + tiefe += 1 + elif klar[i] == "]": + tiefe -= 1 + if tiefe == 0: + try: + for sitz in json.loads(klar[klammer:i + 1]): + if sitz.get("seatId") is not None and sitz.get("userId") is not None: + ergebnis[int(sitz["seatId"])] = str(sitz["userId"]) + except ValueError: + pass + break + stelle = klar.find('"seatResponseDataList"', i) + return ergebnis + + +def profile_je_sitz(text): + """{sitz: profil} - verbindet Sitzliste und Statistiken.""" + werte = statistiken(text) + ergebnis = {} + for sitz, kennung in sitze(text).items(): + if kennung in werte: + ergebnis[sitz] = werte[kennung] + return ergebnis diff --git a/lesen/spot_from_log.py b/lesen/spot_from_log.py index 846a25d..6a07728 100644 --- a/lesen/spot_from_log.py +++ b/lesen/spot_from_log.py @@ -22,6 +22,8 @@ import os import sys import re +import profil + LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") BEAN = re.compile( r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[a-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"') @@ -67,6 +69,7 @@ class Tisch: self.aktion = {} self.button = None self.hand = None + self.profile = {} def neuer_hand(self, hand): if hand != self.hand: @@ -88,7 +91,8 @@ class Tisch: held = [n for n, name in self.namen.items() if name == ME] held_seat = held[0] if held else 5 gegner = [{"seat": s, "stack": self.chips.get(s, bb * 50), - "folded": self.aktion.get(s) == "Fold"} + "folded": self.aktion.get(s) == "Fold", + **({"profile": self.profile[s]} if self.profile.get(s) else {})} for s, name in self.namen.items() if s != held_seat and name] anfrage = { "variant": "NLHE", "bigBlind": bb, "seats": max(self.namen) if self.namen else 6, @@ -106,6 +110,7 @@ class Tisch: def spots(text): """Liefert je eigenem Zug: (Anfrage, Kurzinfo, Raum, Hand).""" tische = {} + profile = profil.profile_je_sitz(text) hole = {} ergebnis = [] for m in BEAN.finditer(text): @@ -118,6 +123,7 @@ def spots(text): if not isinstance(d, dict): continue t = tische.setdefault(raum, Tisch(raum)) + t.profile = profile if cmd == "game.game_alldata": g = d.get("gameInitResponseData") or {} diff --git a/tests/profil_spec.py b/tests/profil_spec.py new file mode 100644 index 0000000..8ac2906 --- /dev/null +++ b/tests/profil_spec.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Spezifikation des Gegnerprofils - geschrieben VOR dem Code. + +Der Client liefert Gegnerstatistiken je Nutzerkennung, und die Sitzliste führt +Sitz, Name und Kennung zusammen. Daraus entsteht ein Profil je Sitz. + +Geprüft wird: Werte werden auf 0..1 normiert, fehlende Felder fliegen raus, +spätere Angaben schlagen frühere, fremde Kennungen tauchen nicht auf. + + python3 tests/profil_spec.py -v +""" +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",): + _q = os.path.join(_w, _u) + if os.path.isdir(_q): + sys.path.append(_q) + +import profil + + +def esc(text): + """Wie im Client-Log: innere Anführungszeichen sind maskiert.""" + return text.replace('"', '\\"') + + +SITZE = esc('"seatResponseDataList":[' + '{"seatId":2,"userName":"SneS77","userId":1662615,"userChips":9.8},' + '{"seatId":4,"userName":"Chicago111","userId":1701711,"userChips":10.6},' + '{"seatId":5,"userName":"mmintel","userId":1671088,"userChips":9.0}]') + +KOMPLETT = esc('"api":"hud_stats","data":{"msg":{' + '"1662615":{"1":{"fold":73,"fta":65,"vpip":29,"pfr":20,"threeBet":9}},' + '"1701711":{"1":{"fold":76,"fta":62,"vpip":26,"pfr":15}},' + '"999999":{"1":{"fold":50,"fta":40,"vpip":11,"pfr":3}}}}') + +OHNE_FTA = esc('"api":"hud_stats","data":{"msg":{"1701711":{"1":{"fold":76,"vpip":26,"pfr":15}}}}') + +KAPUTT = esc('"api":"hud_stats","data":{"msg":{"1701711":{"1":{"mkdir":1,"vpip":120,"pfr":-5}}}}') + + +class Werte(unittest.TestCase): + def test_prozent_wird_zu_anteil(self): + s = profil.statistiken(SITZE + KOMPLETT) + self.assertAlmostEqual(s["1662615"]["vpip"], 0.29, places=4) + self.assertAlmostEqual(s["1662615"]["pfr"], 0.20, places=4) + + def test_foldtobet_aus_dem_feld_fuer_druck(self): + s = profil.statistiken(SITZE + KOMPLETT) + self.assertAlmostEqual(s["1662615"]["foldToBet"], 0.65, places=4) + + def test_ohne_druck_feld_zaehlt_das_gesamte_folden(self): + s = profil.statistiken(SITZE + OHNE_FTA) + self.assertAlmostEqual(s["1701711"]["foldToBet"], 0.76, places=4) + + def test_werte_bleiben_zwischen_null_und_eins(self): + s = profil.statistiken(KAPUTT) + self.assertLessEqual(s["1701711"]["vpip"], 1.0) + self.assertGreaterEqual(s["1701711"]["pfr"], 0.0) + + def test_unbekannte_felder_stoeren_nicht(self): + s = profil.statistiken(KAPUTT) + self.assertIn("vpip", s["1701711"]) + + def test_leerer_text_ergibt_leere_abbildung(self): + self.assertEqual(profil.statistiken(""), {}) + + +class Sitze(unittest.TestCase): + def test_profil_haengt_am_sitz(self): + p = profil.profile_je_sitz(SITZE + KOMPLETT) + self.assertEqual(sorted(p), [2, 4]) + self.assertAlmostEqual(p[2]["vpip"], 0.29, places=4) + + def test_sitz_ohne_statistik_fehlt(self): + p = profil.profile_je_sitz(SITZE + OHNE_FTA) + self.assertNotIn(2, p) + self.assertIn(4, p) + + def test_ohne_sitzliste_leer(self): + self.assertEqual(profil.profile_je_sitz(KOMPLETT), {}) + + +class Reihenfolge(unittest.TestCase): + def test_spaetere_angabe_schlaegt_fruehere(self): + alt = esc('"api":"hud_stats","data":{"msg":{"1701711":{"1":{"vpip":10,"pfr":5}}}}') + neu = esc('"api":"hud_stats","data":{"msg":{"1701711":{"1":{"vpip":40,"pfr":30}}}}') + s = profil.statistiken(alt + " ... " + neu) + self.assertAlmostEqual(s["1701711"]["vpip"], 0.40, places=4) + + +if __name__ == "__main__": + unittest.main(verbosity=2)