Files
pokerfreak-shell/mcp/lobby_adapter.py
T
mmintelandClaude Opus 5.5 0f0d0b725f Grosse Runde: Tempobaender, Sitout beim Beenden, Ergebnis und Statistik, Geld nach Modus und Regel
- Denkzeit in Baendern (trivial/normal/schwer), weiche Kappen, keine zwei gleich
- Sitzen: Gedaechtnis je Raum, Stellen statt Nummern (gelernt aus reserve_Seat), Sitout erkennen
  und zurueck, ein Tisch, keine doppelten Fenster
- Laeufer: Strg-C/Signal/Not-Aus -> Sitout, dann aufraeumen; Wiederaufnahme; Schattenlog je Tag
- Ergebnis je Hand (lesen/ergebnis.py) ins Schattenlog, Statistik (betrieb/statistik.py, MCP stats)
- Geld: Kaufhoehe je Modus (coinType), Fuenftel-Regel angeschlossen (nie 0 Tische trotz Kauf),
  Aufstehen unter 20 BB, Verlustdeckel Tisch/Sitzung, Stakes-Leiter, Ratholing schaltbar
- Tischauswahl nach Staerke (lobby/auswahl.py); Klon: Sitout/I'm Back, Aufstehen per Kreuz
- werkzeuge/messung.py: Aktions-, Groessen- und Gedenkzeitverteilung ueber den Bestand

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

157 lines
5.9 KiB
Python

"""CDP-Adapter für die CoinPoker-Lobby.
Steuert die Lobby-Oberfläche über Text statt Koordinaten via cdp.mjs.
"""
import json
import os
import fenster
import subprocess
import time
_w = os.path.dirname(os.path.abspath(__file__))
while _w != "/" and not os.path.isdir(os.path.join(_w, "hand")):
_w = os.path.dirname(_w)
WURZEL = _w
CDP_SCRIPT = os.path.join(WURZEL, "lobby", "cdp.mjs")
import sys
for _u in ("lobby", "lesen"):
if os.path.join(WURZEL, _u) not in sys.path:
sys.path.insert(0, os.path.join(WURZEL, _u))
import auswahl
def _geoeffnet(vorher, kennung):
"""Belege dafür, dass der Beitritt gewirkt hat: neues Fenster, Fenstertitel,
oder der Raum taucht im Log auf. Ein einzelner Beleg genügt."""
import os as _o
if len(fenster.tischfenster()) > vorher:
return True
if any(kennung in f["titel"] for f in fenster.tischfenster()):
return True
pfad = _o.environ.get("COINPOKER_LOG",
_o.path.expanduser("~/Library/Logs/CoinPoker/main.log"))
try:
with open(pfad, errors="replace") as h:
h.seek(max(0, _o.path.getsize(pfad) - 40_000))
return kennung in h.read()
except OSError:
return False
KLICK_ZEILE = """(() => {
const zeile = document.querySelector('[data-table-id="__ID__"]');
if (!zeile) return "Zeile nicht gefunden";
const knoepfe = [...zeile.querySelectorAll('button,a,div,span')]
.filter(n => n.offsetParent !== null && (n.innerText||"").trim().toLowerCase() === "join")
.sort((a,b)=>{const ra=a.getBoundingClientRect(),rb=b.getBoundingClientRect();
return ra.width*ra.height - rb.width*rb.height;});
if (!knoepfe.length) return "kein Join in der Zeile";
const r = knoepfe[0].getBoundingClientRect();
const o = {bubbles:true, cancelable:true, composed:true, button:0,
clientX:r.x+r.width/2, clientY:r.y+r.height/2};
for (const a of ["pointerdown","mousedown","pointerup","mouseup","click"]) {
knoepfe[0].dispatchEvent(a.startsWith("pointer") ? new PointerEvent(a,o) : new MouseEvent(a,o));
}
return "Join geklickt in Zeile __ID__";
})()"""
def cdp_ausfuehren(args):
"""Führt cdp.mjs mit Argumenten aus und liefert die Textausgabe."""
try:
r = subprocess.run(
["node", CDP_SCRIPT] + args,
capture_output=True,
text=True,
timeout=8,
)
out = (r.stdout or "").strip()
err = (r.stderr or "").strip()
return out if out else (err or "keine Ausgabe")
except subprocess.TimeoutExpired:
return "Fehler: Zeitüberschreitung bei CDP-Aufruf"
except Exception as exc:
return f"Fehler: {exc}"
LEITER = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"archiv", "live", "leiter.json")
def _leiter(guthaben, zeilen):
"""lobby/auswahl.leiter_band mit dem Zustand aus LEITER (Stufe und Bezugsguthaben)."""
try:
with open(LEITER, encoding="utf-8") as f:
zustand = json.load(f)
except (OSError, ValueError):
zustand = {}
band = auswahl.leiter_band(guthaben, zeilen, zustand)
if band:
os.makedirs(os.path.dirname(LEITER), exist_ok=True)
with open(LEITER, "w", encoding="utf-8") as f:
json.dump(zustand, f)
return band
def tisch_oeffnen(reiter, name=None, guthaben=None, sitzt_schon=0, band=None):
"""Wechselt auf den Reiter und öffnet gezielt (name) oder den nach lobby/auswahl.py
weichsten Tisch (Band, Geldregel); ohne Guthaben nur voll/leer/Weichheit."""
cdp_ausfuehren(["--click", reiter])
time.sleep(0.5)
js = """(() => {
const rows = [...document.querySelectorAll(".table-row")];
return JSON.stringify(rows.map(r => ({
id: r.dataset.tableId || "",
players: (r.querySelector(".players")?.innerText || "").trim(),
blinds: (r.querySelector(".blind-amount")?.innerText || "").trim(),
min: (r.querySelector(".buy-in")?.innerText || "").trim(),
avg: (r.querySelector(".avg-stack")?.innerText || "").trim()
})));
})()"""
rohe_tische = cdp_ausfuehren(["--eval", js])
try:
tische = json.loads(rohe_tische)
except Exception:
tische = []
if not tische:
res = cdp_ausfuehren(["--click", "Join"])
return f"{reiter}-Tisch per Standard-Join geöffnet: {res}"
ziel_tisch = None
if name:
name_lower = name.strip().lower()
for t in tische:
if name_lower in t["id"].lower():
ziel_tisch = t
break
if not ziel_tisch:
bekannt = ", ".join(t["id"] for t in tische[:5])
return f"{reiter}-Tisch '{name}' nicht gefunden. Verfügbar: {bekannt}"
if name:
kandidaten = [ziel_tisch]
else:
zeilen = [{"id": t["id"], "spieler": t["players"].split()[0] if t["players"] else None,
"schnitt": t.get("avg"), "blinds": t.get("blinds") or None,
"min": t.get("min") or None} for t in tische]
if band is None and guthaben is not None: # Stakes-Leiter, Stufe bleibt gespeichert
band = _leiter(guthaben, zeilen)
urteile = auswahl.waehlen(zeilen, guthaben=guthaben, sitzt_schon=sitzt_schon, band=band)
nach_id = {t["id"]: t for t in tische}
kandidaten = [nach_id[i] for i in auswahl.gewaehlte(urteile)]
if not kandidaten:
gruende = "; ".join(f"{u['id']}: {u['grund']}" for u in urteile[:5])
return f"{reiter}: kein Tisch nach der Auswahl ({gruende})"
vorher = len(fenster.tischfenster())
for kandidat in kandidaten[:3]:
res = cdp_ausfuehren(["--eval", KLICK_ZEILE.replace("__ID__", kandidat["id"])])
time.sleep(2.0)
if _geoeffnet(vorher, kandidat["id"]):
return (f"{reiter}-Tisch geöffnet: {kandidat['id']} [{kandidat['players']}] "
f"-> {res}")
return f"{reiter}: nach {min(3, len(kandidaten))} Versuchen ging kein Tisch auf"