Auf Windows werden die Schein-Exe-Faelle uebersprungen; dieser Fall laeuft dort mit SCHUBFOLD_EXE und prueft auch die Zeit gegen die halbe Frist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
10 KiB
Python
210 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Spezifikation: Schub/Call am Turniertisch (entscheiden/schubfold_tisch.py, entscheiden/schubfold_lage.py).
|
|
|
|
- Schalter aus (kein TURNIER_SCHUBFOLD oder keine Exe): `zug` gibt immer None, kein Prozess, kein Protokoll.
|
|
- Nur Schub/Fold-Lagen: vor dem Flop, vor uns nur Fold oder all-in, wirksam hoechstens 15 bb, Turnierfeld vorhanden.
|
|
- Antwort der Loesung -> Zug: go=1 -> RAISE auf maxRaiseTo (oder CALL, wenn kein RAISE erlaubt), go=0 -> FOLD;
|
|
Fehlerzeile oder unlesbar -> None.
|
|
- Frist: antwortet die Loesung nicht in Frist x FRIST_ANTEIL, kommt None; der naechste Aufruf startet einen neuen Prozess.
|
|
- Jede gestellte Frage steht im Protokoll (nur anhaengen).
|
|
- Mit der echten Exe (Umgebung SCHUBFOLD_EXE): eine echte Lage gibt einen erlaubten Zug.
|
|
|
|
python3 tests/schubfold_tisch_spec.py -v
|
|
"""
|
|
import json
|
|
import os
|
|
import stat
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
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)
|
|
sys.path.insert(0, os.path.join(_w, "entscheiden"))
|
|
|
|
import schubfold_lage as L # noqa: E402
|
|
import schubfold_tisch as S # noqa: E402
|
|
|
|
|
|
def karte(r, f):
|
|
return {"rank": r, "suit": f}
|
|
|
|
|
|
def anfrage(hero_bb=10.0, davor=(), street="PREFLOP", turnier=True, hero_seat=1, n=6, bb=100.0):
|
|
"""6er-Tisch, Sitze 1..n, Knopf n-2, SB n-1, BB n; Ante 12,5. Hero auf `hero_seat`. `davor`: (Sitz, Aktion, Betrag)."""
|
|
sb_seat, bb_seat = n - 1, n
|
|
hist = [{"seat": s, "action": "POST_ANTE", "amount": 12.5, "street": "PREFLOP"} for s in range(1, n + 1)]
|
|
hist += [{"seat": sb_seat, "action": "POST_SB", "amount": 50.0, "street": "PREFLOP"},
|
|
{"seat": bb_seat, "action": "POST_BB", "amount": bb, "street": "PREFLOP"}]
|
|
stapel = {s: 2000.0 for s in range(1, n + 1)}
|
|
stapel[hero_seat] = hero_bb * bb
|
|
gezahlt = {s: 12.5 + (50.0 if s == sb_seat else bb if s == bb_seat else 0.0) for s in stapel}
|
|
gefaltet = set()
|
|
for s, a, b in davor:
|
|
hist.append({"seat": s, "action": a, "amount": b, "street": "PREFLOP"})
|
|
if a == "FOLD":
|
|
gefaltet.add(s)
|
|
elif b is not None:
|
|
gezahlt[s] = 12.5 + b
|
|
jetzt = {s: stapel[s] - gezahlt[s] for s in stapel}
|
|
hoch = max([bb] + [b for _, a, b in davor if b is not None])
|
|
q = {"variant": "NLHE", "street": street, "bigBlind": bb, "heroSeat": hero_seat, "heroStack": jetzt[hero_seat],
|
|
"heroCards": [karte("ACE", "SPADES"), karte("KING", "SPADES")], "history": hist, "toCall": hoch - gezahlt[hero_seat] + 12.5,
|
|
"legalActions": ["FOLD", "CALL", "RAISE"], "minRaiseTo": 2 * hoch, "maxRaiseTo": jetzt[hero_seat] + gezahlt[hero_seat] - 12.5,
|
|
"villains": [{"seat": s, "stack": jetzt[s], "folded": s in gefaltet} for s in stapel if s != hero_seat]}
|
|
if turnier:
|
|
q["tournament"] = {"payouts": [50.0, 30.0, 20.0], "stacks": [stapel[s] for s in stapel] + [3000.0, 1500.0], "heroIndex": 0}
|
|
return q
|
|
|
|
|
|
class Lage(unittest.TestCase):
|
|
def test_erster_im_topf_kurz_ist_schub_fold(self):
|
|
r = L.lage_aus(anfrage())
|
|
self.assertIsNotNone(r)
|
|
self.assertEqual((r["platz"], r["davor"], r["hand"]), (0, 0, ["As", "Ks"]))
|
|
self.assertEqual(r["feld"], [3000.0, 1500.0])
|
|
|
|
def test_gegen_all_in_davor(self):
|
|
q = anfrage(hero_seat=3, davor=[(1, "ALL_IN", 2000.0 - 12.5), (2, "FOLD", None)])
|
|
q["villains"] = [dict(v, stack=0.0) if v["seat"] == 1 else v for v in q["villains"]]
|
|
r = L.lage_aus(q)
|
|
self.assertIsNotNone(r, L.grund(q))
|
|
self.assertEqual((r["platz"], r["davor"]), (2, 1))
|
|
|
|
def test_keine_schub_fold_lage(self):
|
|
tief = anfrage(hero_bb=30.0)
|
|
nach_flop = anfrage(street="FLOP")
|
|
offen = anfrage(hero_seat=3, davor=[(1, "RAISE", 250.0)])
|
|
ohne_turnier = anfrage(turnier=False)
|
|
zweite = anfrage(davor=[(1, "RAISE", 250.0), (2, "ALL_IN", 1987.5)])
|
|
for q, warum in ((tief, "tiefer als 15 bb"), (nach_flop, "nicht vor dem Flop"), (offen, "nicht all-in"),
|
|
(ohne_turnier, "keine Turnierlage"), (zweite, "zweite Entscheidung")):
|
|
self.assertIsNone(L.lage_aus(q), warum)
|
|
self.assertIn(warum, L.grund(q))
|
|
|
|
|
|
class Antwort(unittest.TestCase):
|
|
def test_schub_ist_alle_chips(self):
|
|
q = anfrage()
|
|
r = S.antwort_aus("ok;go=1;p=0.9100;breite=0.2;ev_fold=0.1;ev_go=0.2;ms=900;start=warm", q)
|
|
self.assertEqual((r["action"], r["size"]), ("RAISE", q["maxRaiseTo"]))
|
|
self.assertIn("warm", r["reason"])
|
|
|
|
def test_schub_ohne_raise_ist_call(self):
|
|
q = dict(anfrage(), legalActions=["FOLD", "CALL"])
|
|
self.assertEqual(S.antwort_aus("ok;go=1;p=1;breite=0.1;ev_fold=0;ev_go=1;ms=1;start=warm", q)["action"], "CALL")
|
|
|
|
def test_fold(self):
|
|
r = S.antwort_aus("ok;go=0;p=0.1000;breite=0.2;ev_fold=0.2;ev_go=0.1;ms=900;start=warm", anfrage())
|
|
self.assertEqual(r["action"], "FOLD")
|
|
|
|
def test_fehler_und_unlesbar_sind_keine_antwort(self):
|
|
for z in ("fehler;Preise oder Stapel ungueltig", "", None, "ok;go=1", "ok;go=x;p=a;ev_fold=;ev_go="):
|
|
self.assertIsNone(S.antwort_aus(z, anfrage()), z)
|
|
|
|
|
|
def falsche_exe(ordner, text):
|
|
"""Eine Schein-Loesung (Python) unter dem Namen der Exe."""
|
|
p = os.path.join(ordner, S.EXE)
|
|
with open(p, "w", encoding="utf-8") as f:
|
|
f.write(f"#!{sys.executable}\nimport sys, time\n{text}\n")
|
|
os.chmod(p, os.stat(p).st_mode | stat.S_IEXEC)
|
|
return p
|
|
|
|
|
|
@unittest.skipIf(sys.platform == "win32", "Schein-Exe als Python-Skript nur unter Unix")
|
|
class Schalter(unittest.TestCase):
|
|
def tearDown(self):
|
|
S.einrichten(None)
|
|
|
|
def test_aus_ohne_schalter(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
ziel = os.path.join(d, "log.jsonl")
|
|
self.assertFalse(S.einrichten(None))
|
|
self.assertIsNone(S.zug(json.dumps(anfrage()), 5.0, ziel=ziel))
|
|
self.assertFalse(os.path.exists(ziel))
|
|
|
|
def test_aus_ohne_exe(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
self.assertFalse(S.einrichten(d))
|
|
self.assertFalse(S.an())
|
|
|
|
def test_an_fragt_und_protokolliert(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
falsche_exe(d, "for z in sys.stdin:\n sys.stdout.write('ok;go=1;p=0.95;breite=0.3;ev_fold=0.1;ev_go=0.2;ms=5;start=' + ('warm' if 'tafel=' in z else 'kalt') + '\\n'); sys.stdout.flush()")
|
|
open(os.path.join(d, S.TAFEL), "wb").close()
|
|
ziel = os.path.join(d, "log.jsonl")
|
|
self.assertTrue(S.einrichten(d))
|
|
q = anfrage()
|
|
r = S.zug(json.dumps(q), 10.0, "Tisch", "123", ziel=ziel)
|
|
self.assertEqual((r["action"], r["size"]), ("RAISE", q["maxRaiseTo"]))
|
|
self.assertIn("warm", r["reason"])
|
|
# Cash und tiefe Lagen fragt er nicht
|
|
self.assertIsNone(S.zug(json.dumps(anfrage(turnier=False)), 10.0, ziel=ziel))
|
|
self.assertIsNone(S.zug(json.dumps(anfrage(hero_bb=40.0)), 10.0, ziel=ziel))
|
|
with open(ziel, encoding="utf-8") as f:
|
|
zeilen = [json.loads(z) for z in f]
|
|
self.assertEqual(len(zeilen), 1)
|
|
self.assertEqual((zeilen[0]["hand"], zeilen[0]["zug"]["action"]), ("123", "RAISE"))
|
|
|
|
def test_frist_reisst_dann_neuer_prozess(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
marke = os.path.join(d, "gestartet")
|
|
falsche_exe(d, f"open({marke!r}, 'a').write('x')\nn = len(open({marke!r}).read())\n"
|
|
"for z in sys.stdin:\n time.sleep(30 if n == 1 else 0)\n"
|
|
" sys.stdout.write('ok;go=0;p=0.1;breite=0.3;ev_fold=0.2;ev_go=0.1;ms=5;start=kalt\\n'); sys.stdout.flush()")
|
|
ziel = os.path.join(d, "log.jsonl")
|
|
S.einrichten(d)
|
|
t0 = time.time()
|
|
self.assertIsNone(S.zug(json.dumps(anfrage()), 2.0, ziel=ziel))
|
|
self.assertLess(time.time() - t0, 2.0 * S.FRIST_ANTEIL + 0.8)
|
|
self.assertEqual(S.zug(json.dumps(anfrage()), 10.0, ziel=ziel)["action"], "FOLD")
|
|
with open(marke) as f:
|
|
self.assertEqual(f.read(), "xx")
|
|
with open(ziel, encoding="utf-8") as f:
|
|
roh = [json.loads(z)["roh"] for z in f]
|
|
self.assertEqual(roh[0], "keine Antwort in der Frist")
|
|
|
|
|
|
@unittest.skipUnless(os.environ.get("SCHUBFOLD_EXE"), "echte Exe: Umgebung SCHUBFOLD_EXE=<Pfad> (und SCHUBFOLD_TAFEL)")
|
|
class EchteExe(unittest.TestCase):
|
|
def test_echte_lage_gibt_erlaubten_zug(self):
|
|
import subprocess
|
|
q = anfrage(hero_bb=8.0)
|
|
zeile = L.zeile(L.lage_aus(q), S.AUSTEILUNGEN, S.FAEDEN, os.environ.get("SCHUBFOLD_TAFEL"))
|
|
aus = subprocess.run([os.environ["SCHUBFOLD_EXE"]], input=zeile + "\n", capture_output=True, text=True, timeout=60).stdout
|
|
r = S.antwort_aus(aus.splitlines()[0], q)
|
|
self.assertIn(r["action"], q["legalActions"])
|
|
self.assertEqual(r["action"], "RAISE", "AKs mit 8 bb als Erster im Topf")
|
|
|
|
def test_ganzer_weg_ueber_den_schalter(self):
|
|
"""Wie am Tisch: Ordner mit der Exe (und Tafel daneben) einrichten, Frage stellen, Zug und Protokoll."""
|
|
exe = os.environ["SCHUBFOLD_EXE"]
|
|
if os.path.basename(exe) != S.EXE:
|
|
self.skipTest(f"Exe heisst nicht {S.EXE}")
|
|
with tempfile.TemporaryDirectory() as d:
|
|
ziel = os.path.join(d, "log.jsonl")
|
|
try:
|
|
self.assertTrue(S.einrichten(os.path.dirname(exe)))
|
|
t0 = time.time()
|
|
q = anfrage(hero_bb=8.0)
|
|
r = S.zug(json.dumps(q), 20.0, "Tisch", "1", ziel=ziel)
|
|
dauer = time.time() - t0
|
|
finally:
|
|
S.einrichten(None)
|
|
with open(ziel, encoding="utf-8") as f:
|
|
zeile = json.loads(f.readline())
|
|
self.assertIsNotNone(r, f"keine Antwort nach {dauer:.1f} s: {zeile['roh']}")
|
|
self.assertEqual((r["action"], r["size"]), ("RAISE", q["maxRaiseTo"]))
|
|
self.assertLess(dauer, 20.0 * S.FRIST_ANTEIL)
|
|
self.assertTrue(zeile["roh"].startswith("ok;"), zeile["roh"])
|
|
erwartet = "warm" if os.path.exists(os.path.join(os.path.dirname(exe), S.TAFEL)) else "kalt"
|
|
self.assertIn("start=" + erwartet, zeile["roh"])
|
|
print(f"\nganzer Weg: {dauer:.2f} s, {zeile['roh']}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|