Files
pokerfreak/messung/fremd/4_regeln/hh.py
T

336 lines
14 KiB
Python

#!/usr/bin/env python3
"""Fremdpruefung Punkt 4: eine Hand im hhDealer-Textformat lesen und mit pokerkit (Universitaet Toronto,
unabhaengige Regelmaschine) nachspielen. Nur Funktionen, keine Namen im Ergebnis (Sitznummern).
parse(text) -> dict (Sitze, Posten, Aktionen je Strasse, Karten, Gewinne laut Text)
replay(h) -> dict mit pokerkit-Ergebnis (Einsatz, Bruttoauszahlung je Topf und Sitz, Rueckgabe)
vergleich(h, r) -> Liste (Klasse, Text) der Abweichungen zwischen Text und pokerkit
Betraege intern in Cent (ganze Zahlen); jede Zahl, die kein ganzer Cent ist, wird als 'kein_cent' gemeldet.
"""
import itertools
import re
from pokerkit import Automation, Mode, NoLimitTexasHoldem, StandardHighHand, Card, Deck
B = r"₮([\d.,]+)"
RE_KOPF = re.compile(r"^CoinPoker Hand #(\d+): .*?\(₮([\d.]+)/₮([\d.]+)(?: - Ante ₮([\d.]+))?.*?\) - (\d{4}/\d\d/\d\d \d\d:\d\d:\d\d)")
RE_KNOPF = re.compile(r"Seat #(\d+) is the button")
RE_SITZ = re.compile(r"^Seat (\d+): (.+) \(" + B + r" in chips")
RE_AKT = re.compile(r"^(.+?): (posts the ante|posts small blind|posts big blind|posts straddle|posts|calls|bets|raises|checks|folds)"
r"(?: " + B + r")?(?: to " + B + r")?( and is all-in)?")
RE_ZUR = re.compile(r"^Uncalled bet \(" + B + r"\) returned to (.+)$")
RE_ZEIGT = re.compile(r"^(.+?): shows \[(\w\w) (\w\w)\]")
RE_KOLL = re.compile(r"^(.+?) collected " + B + r" from pot")
RE_TOPF = re.compile(r"^Total pot " + B + r" \| Rake " + B)
RE_BRETT = re.compile(r"\[([^\]]*)\]")
AUTOM = (Automation.ANTE_POSTING, Automation.BET_COLLECTION, Automation.BLIND_OR_STRADDLE_POSTING,
Automation.CARD_BURNING, Automation.HAND_KILLING, Automation.CHIPS_PUSHING, Automation.CHIPS_PULLING,
Automation.HOLE_CARDS_SHOWING_OR_MUCKING, Automation.RUNOUT_COUNT_SELECTION)
def cent(s):
"""'1.23' -> 123; Nicht-Cent-Betraege liefern (Wert, False)."""
if s is None:
return 0, True
x = float(s.replace(",", "")) * 100.0
return int(round(x)), abs(x - round(x)) < 1e-6
class Fehl(Exception):
pass
def parse(text):
zeilen = [z.rstrip("\r") for z in text.strip().splitlines()]
m = RE_KOPF.match(zeilen[0])
if not m:
raise Fehl("kopf")
h = {"id": m.group(1), "bb": cent(m.group(3))[0], "sb": cent(m.group(2))[0], "ante": cent(m.group(4))[0] if m.group(4) else 0,
"zeit": m.group(5), "kopf_art": ("plain" if m.group(4) is None else ("ante0" if cent(m.group(4))[0] == 0 else "ante")), "sitze": {}, "knopf": None, "posten": [], "akt": [], "board": [], "brett_str": [],
"zeigt": {}, "koll": {}, "zurueck": {}, "topf_text": None, "rake_text": None, "kein_cent": False,
"summary_board": [], "allin_text": set()}
strasse = 0
phase = "kopf"
h["rit"] = any(z.startswith("*** FIRST ") or z.startswith("Hand was run twice") for z in zeilen)
h["cashout"] = any("EV Cashout" in z or "Cashout Risk" in z for z in zeilen)
for z in zeilen[1:]:
if z.startswith("*** HOLE CARDS"):
phase = "spiel"
continue
if z.startswith("*** FLOP"):
strasse = 1
h["board"] += RE_BRETT.findall(z)[0].split()
h["akt"].append(("STR", 1, None, None))
continue
if z.startswith("*** TURN"):
strasse = 2
h["board"] += RE_BRETT.findall(z)[-1].split()
h["akt"].append(("STR", 2, None, None))
continue
if z.startswith("*** RIVER"):
strasse = 3
h["board"] += RE_BRETT.findall(z)[-1].split()
h["akt"].append(("STR", 3, None, None))
continue
if z.startswith("*** SHOW DOWN"):
continue
if z.startswith("*** SUMMARY"):
phase = "summe"
continue
if phase == "summe":
mt = RE_TOPF.match(z)
if mt:
h["topf_text"], ok1 = cent(mt.group(1))
h["rake_text"], ok2 = cent(mt.group(2))
h["kein_cent"] |= not (ok1 and ok2)
elif z.startswith("Board"):
h["summary_board"] = RE_BRETT.findall(z)[0].split() if RE_BRETT.findall(z) else []
continue
if RE_KNOPF.search(z):
h["knopf"] = int(RE_KNOPF.search(z).group(1))
continue
ms = RE_SITZ.match(z)
if ms and phase == "kopf":
st, ok = cent(ms.group(3))
h["kein_cent"] |= not ok
h["sitze"][ms.group(2)] = (int(ms.group(1)), st)
continue
mz = RE_ZEIGT.match(z)
if mz:
h["zeigt"][mz.group(1)] = [mz.group(2), mz.group(3)]
continue
mk = RE_KOLL.match(z)
if mk:
v, ok = cent(mk.group(2))
h["kein_cent"] |= not ok
h["koll"][mk.group(1)] = h["koll"].get(mk.group(1), 0) + v
continue
mr = RE_ZUR.match(z)
if mr:
v, ok = cent(mr.group(1))
h["kein_cent"] |= not ok
h["zurueck"][mr.group(2)] = h["zurueck"].get(mr.group(2), 0) + v
h["akt"].append(("ZUR", mr.group(2), v, None))
continue
ma = RE_AKT.match(z)
if ma and ma.group(1) in h["sitze"]:
was = ma.group(2)
a1, ok1 = cent(ma.group(3))
a2, ok2 = cent(ma.group(4))
h["kein_cent"] |= not (ok1 and ok2)
if ma.group(5):
h["allin_text"].add(ma.group(1))
if was.startswith("posts"):
h["posten"].append((ma.group(1), was, a1))
else:
h["akt"].append((was, ma.group(1), a1, a2))
return h
ALLE = [r + s for r in "23456789TJQKA" for s in "cdhs"]
STRASSE_BIS = (0, 3, 4, 5)
def replay(h):
"""pokerkit-Ablauf. Rueckgabe: dict oder wirft Fehl(grund)."""
sitze = h["sitze"]
if len(sitze) < 2:
raise Fehl("zu_wenig_spieler")
knopf = h["knopf"]
namen = sorted(sitze, key=lambda nm: (sitze[nm][0] - knopf - 1) % 10) # ab Sitz nach dem Knopf
if h.get("rit"):
raise Fehl("run_it_twice")
if h.get("cashout"):
raise Fehl("ev_cashout")
sbn = next((nm for nm, w, _ in h["posten"] if w == "posts small blind"), None)
bbn = next((nm for nm, w, _ in h["posten"] if w == "posts big blind"), None)
# Straddle (posts straddle) oder zweiter 'posts big blind' (Spaetblind): nur als UTG-Straddle abbildbar
extra = [(nm, w, v) for nm, w, v in h["posten"] if w == "posts straddle"]
zweite_bb = [(nm, w, v) for nm, w, v in h["posten"] if w == "posts big blind"][1:]
for nm, w, v in h["posten"]:
if w not in ("posts the ante", "posts small blind", "posts big blind", "posts straddle"):
raise Fehl("sonderposten")
if bbn is None:
raise Fehl("kein_bb")
if sbn is None:
raise Fehl("kein_sb")
erster = next((a[1] for a in h["akt"] if a[0] in ("folds", "checks", "calls", "bets", "raises")), None)
strad = None
if len(extra) + len(zweite_bb) > 1:
raise Fehl("sonderposten_mehrere")
if extra or zweite_bb:
strad = (extra or zweite_bb)[0]
if erster == strad[0]:
raise Fehl("sonderposten_spaetblind_vorn")
i0 = namen.index(sbn)
ordnung = namen[i0:] + namen[:i0]
n = len(ordnung)
if ordnung[1] != bbn:
raise Fehl("bb_nicht_neben_sb")
if strad is not None:
if n < 3 or ordnung[2] != strad[0]:
raise Fehl("sonderposten_spaetblind" if zweite_bb else "straddle_nicht_utg")
antes = {nm: 0 for nm in namen}
blind = {}
for nm, w, v in h["posten"]:
if w == "posts the ante":
antes[nm] += v
elif w == "posts big blind" and nm != bbn:
blind[nm] = v
elif w == "posts straddle":
blind[nm] = v
else:
blind[nm] = v
pk_namen = list(ordnung) if n > 2 else [ordnung[1], ordnung[0]]
if n > 2:
blinds_arg = [blind[sbn], blind[bbn]] + ([blind[strad[0]]] if strad else []) + [0] * (n - 2 - (1 if strad else 0))
else:
blinds_arg = [blind[sbn], blind[bbn]]
stacks = [sitze[nm][1] for nm in pk_namen]
ante_arg = [antes[nm] for nm in pk_namen]
st = NoLimitTexasHoldem.create_state(AUTOM, False, ante_arg, blinds_arg, max(h["bb"], 1), stacks, n,
mode=Mode.CASH_GAME)
board = h["board"]
gefoldet = {a[1] for a in h["akt"] if a[0] == "folds"}
belegt = set(c for k in h["zeigt"].values() for c in k) | set(board)
im_sd = [nm for nm in pk_namen if nm not in gefoldet]
zeigend = [nm for nm in im_sd if nm in h["zeigt"]]
hole = {nm: "".join(h["zeigt"][nm]) for nm in pk_namen if nm in h["zeigt"]}
schwelle = None
if len(board) == 5 and zeigend:
schwelle = min(StandardHighHand.from_game(hole[nm], "".join(board)) for nm in zeigend)
frei = [c for c in ALLE if c not in belegt]
unbekannt_im_sd = []
for nm in pk_namen:
if nm in hole:
continue
gew = None
if nm in im_sd and len(board) == 5 and len(im_sd) >= 2:
unbekannt_im_sd.append(nm)
# schwaechstes Blatt: erst billig (zwei niedrige freie Karten), notfalls gesucht
kand = [c for c in frei if c[0] in "2345678"]
best = None
for a, b in itertools.combinations(kand, 2):
x = StandardHighHand.from_game(a + b, "".join(board))
if schwelle is None or x < schwelle:
best = (a, b)
break
if best is None:
best = min(itertools.combinations(frei, 2),
key=lambda ab: StandardHighHand.from_game(ab[0] + ab[1], "".join(board)))
gew = best
else:
gew = (frei[0], frei[1])
hole[nm] = gew[0] + gew[1]
frei = [c for c in frei if c not in gew]
belegt |= set(gew)
for nm in pk_namen:
if not st.can_deal_hole():
raise Fehl("deal_hole")
st.deal_hole(hole[nm])
abw = []
def brett_legen(bis):
nonlocal frei
while st.can_burn_card() or st.can_deal_board():
have = sum(len(x) for x in st.board_cards)
if have >= bis:
return
if st.can_burn_card():
st.burn_card(frei[0])
frei = frei[1:]
continue
k = 3 if have == 0 else 1
st.deal_board("".join(board[have:have + k]))
vorher = None
for a in h["akt"]:
was = a[0]
if was == "STR":
if st.actor_index is not None:
raise Fehl("strasse_zu_frueh")
brett_legen(STRASSE_BIS[a[1]])
continue
if was == "ZUR":
continue
nm = a[1]
if st.actor_index is None:
raise Fehl("kein_akteur_mehr")
if pk_namen[st.actor_index] != nm:
if was == "checks" and vorher == nm:
abw.append(("text_doppelte_aktion", "checks direkt nach eigener Aktion"))
continue
raise Fehl("reihenfolge")
vorher = nm
if was == "folds":
st.fold()
elif was == "checks":
if st.checking_or_calling_amount:
raise Fehl("check_statt_call")
st.check_or_call()
elif was == "calls":
erw = st.checking_or_calling_amount
if erw != a[2]:
abw.append(("call_betrag", f"text {a[2]} pokerkit {erw}"))
st.check_or_call()
elif was == "bets":
if not st.can_complete_bet_or_raise_to(a[2]):
raise Fehl("bet_unzulaessig")
st.complete_bet_or_raise_to(a[2])
elif was == "raises":
if not st.can_complete_bet_or_raise_to(a[3]):
if a[3] <= max(st.bets):
abw.append(("raise_unter_gebot_als_call", f"raises to {a[3]} bei Gebot {max(st.bets)} = Call"))
st.check_or_call()
else:
raise Fehl("raise_unzulaessig")
else:
st.complete_bet_or_raise_to(a[3])
brett_legen(5)
if st.status:
f = Fehl("hand_nicht_zu_ende")
f.state = st
raise f
from pokerkit.state import ChipsPushing
brutto = [0] * n
toepfe = []
for op in st.operations:
if isinstance(op, ChipsPushing):
toepfe.append(sum(op.amounts))
for i, v in enumerate(op.amounts):
brutto[i] += v
einsatz = [stacks[i] - st.stacks[i] + brutto[i] for i in range(n)]
return {"namen": pk_namen, "einsatz": {pk_namen[i]: einsatz[i] for i in range(n)},
"brutto": {pk_namen[i]: brutto[i] for i in range(n)}, "toepfe": toepfe,
"end": {pk_namen[i]: st.stacks[i] for i in range(n)}, "start": {pk_namen[i]: stacks[i] for i in range(n)},
"abw": abw, "n": n, "ops": [str(o) for o in st.operations], "unbekannt_sd": unbekannt_im_sd, "sd": len(im_sd) >= 2, "lebende": im_sd}
def text_einsatz(h):
"""Einsatz je Spieler laut Text: Antes + Blinds + Aktionen - Rueckgabe."""
ein = {nm: 0 for nm in h["sitze"]}
auf = {nm: 0 for nm in h["sitze"]}
for nm, w, v in h["posten"]:
ein[nm] += v
if w != "posts the ante":
auf[nm] += v
for a in h["akt"]:
if a[0] == "STR":
auf = {nm: 0 for nm in h["sitze"]}
elif a[0] == "ZUR":
ein[a[1]] -= a[2]
elif a[0] in ("calls", "bets"):
auf[a[1]] += a[2]
ein[a[1]] += a[2]
elif a[0] == "raises":
ein[a[1]] += a[3] - auf[a[1]]
auf[a[1]] = a[3]
return ein
def hand_ende(h):
"""Strasse, auf der die Hand laut Text endete (0..3); Showdown ja/nein laut Text."""
return max([a[1] for a in h["akt"] if a[0] == "STR"] or [0])