Hülle: Zustand, Entscheiden, Klicken, Denkzeit, Archiv

This commit is contained in:
2026-10-28 13:53:39 +01:00
commit 86d00e9d72
28 changed files with 12171 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
__pycache__/
scratch/
.DS_Store
+41
View File
@@ -0,0 +1,41 @@
# pokerfreak-shell
Die Hände zum Kopf: liest den Client mit, holt beim Kern die Entscheidung, klickt sie mit
menschlichem Zeitgefühl und protokolliert alles.
## Die Grenze zum Kern
Hier steckt **kein Spielverstand**. Der liegt in `pokerfreak` (Rust) im Nachbarordner und wird
allein über zwei Dinge berührt:
* den **Vertrag** – Kopie in `docs/VERTRAG.md`, eingefroren
* das gebaute Programm, standardmässig `../pokerfreak/target/release/pokerfreak`,
überschreibbar über `COINPOKER_KERN` (Quellordner: `COINPOKER_KERN_QUELLE`)
Der Kern bleibt rein: keine Abhängigkeiten, keine Clientkenntnis, kein Zeitgefühl. Deshalb dürfen
beide Seiten unabhängig voneinander leben – und der Kern darf nicht mit diesem Haufen vermischt
werden.
## Ordner
| Ordner | Aufgabe |
|---|---|
| `lesen/` | Zustand aus dem Client-Log, Formatverzeichnis |
| `entscheiden/` | dünne Brücke zum Kern (Aufruf, Antwort lesen) |
| `hand/` | Klicken, Tasten, Fensterzuordnung, Denkzeit |
| `lobby/` | Oberfläche über das Debug-Port steuern (Text statt Koordinaten) |
| `korpus/` | Archiv sichern, Abgleich gegen die Client-Bewertung |
| `betrieb/` | der Kreislauf: Schatten oder Klicken |
| `tests/` | Spezifikationen |
| `archiv/` | gesicherte Logs – der Client rotiert seine eigene Datei weg |
| `mcp/` | folgt: MCP-Server als Werkzeugkasten für Agenten |
## Start
```bash
python3 tests/denkzeit_spec.py # Prüfungen der Denkzeit
python3 betrieb/runner.py --replay # gegen das Archiv, ohne Tisch
python3 betrieb/runner.py --live # Schatten: sagen, nicht klicken
python3 betrieb/runner.py --live --act # klickt auch
touch scratch/stop # Not-Aus fürs Klicken
```
+25
View File
@@ -0,0 +1,25 @@
# Tastentest 10:50:54 | Tasten ['f', 'c', 'r', 'space'] | Sendearten ['an Prozess', 'global']
=== Versuch 1 | 10:51:03 | f an Prozess | Hand 166247100237 None Call 0.1
Taste 'f' (code 3) gesendet an [69791] (an Prozess)
keine Reaktion
=== Versuch 2 | 10:51:41 | c an Prozess | Hand 166247100238 None Call 0.05
Taste 'c' (code 8) gesendet an [69791] (an Prozess)
keine Reaktion
=== Versuch 3 | 10:51:55 | r an Prozess | Hand 166247100238 None Call 0.4
Taste 'r' (code 15) gesendet an [69791] (an Prozess)
keine Reaktion
=== Versuch 4 | 10:51:59 | space an Prozess | Hand 166247100238 None Call 0.0
Taste 'space' (code 49) gesendet an [49974, 69791] (an Prozess)
keine Reaktion
=== Versuch 5 | 10:52:10 | f global | Hand 166247100238 None Call 0.35
Taste 'f' (code 3) gesendet an [69791] (global)
keine Reaktion
=== Versuch 6 | 10:52:47 | c global | Hand 166247100239 None Call 0.2
Taste 'c' (code 8) gesendet an [69791] (global)
keine Reaktion
File diff suppressed because one or more lines are too long
+35
View File
@@ -0,0 +1,35 @@
# Probe gestartet 10:25:24, 35.0 min
=== Schuss 1 | 10:27:21 | Hand 166270900139 | 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709
Call 0.2 Zeit 16s
Kandidat A Kontrolle: Token anfordern
gesendet OK
Reaktionen: 7
2026-10-28 10:27:21:931 [info] [UNITY] Sending event - firebase_token_response
2026-10-28 10:27:22:205 [info] [UNITY] Sending event - firebase_token_response
[Method] -> SendMessageToPipe - {"EventName":"receive_from_table","RequestId":null,"Data":{"event_type":"track_events","action":"GAME_BET_RAISE_ACTION_TYPE_Desktop","data":{"custom_bet":0.5,"big_blind
[Method] -> SendExtensionMessageToConnector - RoomName 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709 RequestId - game.user_action
[Method] -> TransformToBean - RoomName - 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709 cmd - game.dealer_chat_action
[Method] -> TransformToBean - RoomName - 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709 cmd - game.advance_player_action
[Method] -> SendMessageToPipe - {"EventName":"extension_event","RequestId":null,"Data":{"cmd_bean":{"BeanData":"{\"advanceActionId\":null,\"userTurnOptions\":{\"3\":null,\"4\":null,\"6\":[],\"5\":[],\
=== Schuss 2 | 10:29:35 | Hand 166270900143 | 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709
Call 0.0 Zeit 16s
Kandidat B send_to_table + action table_layout
gesendet OK
Reaktionen: 1
2026-10-28 10:29:35:829 [info] [UNITY] Sending event - firebase_token_response
=== Schuss 3 | 10:30:28 | Hand 166270900144 | 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709
Call 0.15 Zeit 16s
Kandidat C send_to_table + api table_settings
gesendet OK
Reaktionen: 1
2026-10-28 10:30:28:332 [info] [UNITY] Sending event - firebase_token_response
=== Schuss 4 | 10:32:53 | Hand 166270900146 | 14R 31st NL 0.05-0.10 EV-INRIT-(A) 1662709
Call 0.75 Zeit 16s
Kandidat D send_to_table + centrifuge player_action
gesendet OK
Reaktionen: 1
2026-10-28 10:32:53:765 [info] [UNITY] Sending event - firebase_token_response
+3376
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
667525729 2930467 /Users/marcmintel/.zcode/workspace/draft-3702f8c3-daf1-4205-b3eb-d991a9581c99/korpus/main-2026-10-28_12-17.log
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Der Kreislauf: Zustand lesen, entscheiden, protokollieren - optional klicken.
python3 runner.py --replay [dateien...] # ohne Tisch, gegen das Archiv
python3 runner.py --live [--act] # am Tisch; --act klickt auch
Ohne --act läuft er im Schatten: er sagt an, du klickst. Jede Entscheidung
landet in scratch/shadow.jsonl. Eine Datei scratch/stop schaltet das Klicken
ab, ohne den Lauf zu beenden.
Sicherungen beim Klicken: nie aussetzen, nie zweimal für denselben Zug, nie
bei fremdem Zug (der Zug muss frisch sein), und nur im richtigen Fenster.
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import glob
import json
import os
import sys
import random
import sys
import time
import act
import decide
import denkzeit
import fenster
import spot_from_log
BASE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
SHADOW = os.path.join(BASE, "scratch", "shadow.jsonl")
TAIL = 400_000
FRISCH = 3.0 # Sekunden: so alt darf der Zug beim Klicken sein
def fingerprint(zeile, raum, hand):
d = json.loads(zeile)
karten = "".join(f"{c['rank'][:1]}{c['suit'][:1]}" for c in d["heroCards"])
return (raum, hand, d["street"], round(d["pot"], 4), round(d["toCall"], 4), karten,
tuple(d.get("allowedSizes") or ()))
def buchen(zeile, kurz, antwort, geklickt=None, hinweis="", gedenkzeit=0.0):
eintrag = {"zeit": time.strftime("%Y-%m-%d %H:%M:%S"), "kurz": kurz,
"anfrage": json.loads(zeile), "antwort": antwort, "geklickt": geklickt,
"gedenkzeit_s": round(gedenkzeit, 2)}
os.makedirs(os.path.dirname(SHADOW), exist_ok=True)
with open(SHADOW, "a") as f:
f.write(json.dumps(eintrag, ensure_ascii=False) + "\n")
marke = antwort.get("action", "?")
if antwort.get("size"):
marke += f" {antwort['size']}"
klick = f" -> klickte {geklickt}" if geklickt else (f" ({hinweis})" if hinweis else "")
warte = f" nach {gedenkzeit:.1f}s" if gedenkzeit else ""
print(f"{time.strftime('%H:%M:%S')} {marke:<10} {antwort.get('confidence', 0):<5} {kurz}{klick}{warte}")
print(f"{'':10} {antwort.get('reason', '')[:90]}")
def replay(pfade):
zeilen = spot_from_log.aus_dateien(pfade)
gesehen, offen = set(), []
for zeile, kurz, raum, hand, _ in zeilen:
f = fingerprint(zeile, raum, hand)
if f in gesehen:
continue
gesehen.add(f)
offen.append((zeile, kurz))
print(f"{len(offen)} verschiedene eigene Züge im Archiv\n")
for (zeile, kurz), antwort in zip(offen, decide.entscheide([z for z, _ in offen])):
buchen(zeile, kurz, antwort)
def live(klicken=False):
print("beobachte live" + (" und klicke" if klicken else " (Schatten)") + " ...")
profil = denkzeit.profil_aus_log(sorted(glob.glob(os.path.join(WURZEL, "archiv", "*.log"))))
zufall = random.Random()
print(f"Denkzeit-Profil: Median {profil['median_ms']:.0f} ms, "
f"Untergrenze {profil['min_ms']:.0f} ms")
stand, gesehen = None, set()
while True:
try:
groesse = os.path.getsize(LOG)
except OSError:
time.sleep(0.5)
continue
if groesse == stand:
time.sleep(0.3)
continue
stand = groesse
with open(LOG, errors="replace") as f:
f.seek(max(0, groesse - TAIL))
text = f.read()
for zeile, kurz, raum, hand, takt in spot_from_log.spots(text):
f = fingerprint(zeile, raum, hand)
if f in gesehen:
continue
gesehen.add(f)
gesehen_zeit = time.time()
anfrage = json.loads(zeile)
antwort = decide.entscheide([zeile])[0]
geklickt, hinweis, gedenkzeit = None, "", 0.0
if klicken:
if act.gestoppt():
hinweis = "gestoppt"
elif antwort.get("action") in ("ABSTAIN", None):
hinweis = "aussetzen"
elif time.time() - gesehen_zeit > FRISCH:
hinweis = "Zug zu alt"
elif fenster.rect_fuer(raum) is None:
hinweis = "kein Fenster"
else:
knapp = denkzeit.knappheit(anfrage, antwort)
gedenkzeit = denkzeit.mit_uhr(
denkzeit.wartezeit(knapp, profil, zufall), takt) / 1000.0
geklickt = act.ausfuehren(antwort, raum,
gedenkzeit - (time.time() - gesehen_zeit))
buchen(zeile, kurz, antwort, geklickt, hinweis, gedenkzeit)
stand = None # nach dem Zug neu einlesen
break
if len(gesehen) > 4000:
gesehen.clear()
def main():
args = sys.argv[1:]
if "--live" in args:
live("--act" in args)
return
pfade = [a for a in args if not a.startswith("--")]
if not pfade:
pfade = sorted(glob.glob(os.path.join(WURZEL, "archiv", "*.log")))
if not pfade:
print("kein Archiv gefunden - erst 'python3 korpus.py' laufen lassen")
return
replay(pfade)
if __name__ == "__main__":
main()
+64
View File
@@ -0,0 +1,64 @@
# Prompt 2: Vertiefung von pokerfreak
Zweiter Auftrag an denselben Agenten, im **bestehenden Repo**. Vertrag bleibt eingefroren.
---
## Ziel
Mach den Kern **postflop besser** und **um Short Deck reicher**. Beides im vorhandenen Aufbau,
mit denselben Regeln wie beim ersten Auftrag.
## Unverändert
- `VERTRAG.md` ist eingefroren: keine Feldnamen ändern, keine Felder entfernen,
höchstens **optionale** Erweiterungsfelder ergänzen und dokumentieren.
- Nur Standardbibliothek, keine Abhängigkeiten.
- Funktionaler Stil, Mikrodateien, eine Datei = ein Begriff.
- Spezifikation zuerst: erst die Testreihe (Terminal läuft rot), dann implementieren, dann aufräumen.
- `ABSTAIN` bleibt erlaubt und erwünscht. Nie eine Aktion außerhalb von `legalActions`.
- Keine Diskussion über Räume, HUDs oder Erlaubtheit.
## Meilenstein 1: Postflop-Qualität
Der Postflop-Teil ist die bekannte Schwäche – er ist heute eine reine Bruchpunkt-Regel gegen eine
grobe Range. Verbessere ihn in dieser Reihenfolge, jeder Schritt mit eigenen Tests:
1. **Handbewertung nach Board-Textur**: Board-Karten, Farbe, Verbindungen und Paarungen
bestimmmen, wie die eigene Hand einzuordnen ist (Top-Paar gut getroffen vs. nur hoch).
2. **Range-Verengung aus der beobachteten Aktion**: Wer vor dem Flop erhöht hat, hat eine andere
Range als wer nur mitgegangen ist. Nutze den Ablauf der Aktionen, nicht nur die Stacks.
3. **Halbbluff-Logik mit Fold-Equity**: Erwartungswert eines Raise = Gewinn durch Aufgabe plus
Gewinn am Showdown. `odds/fold_equity.rs` ist vorhanden, aber nicht angeschlossen.
4. **Mehrweg-Pots**: Bei drei oder mehr Gegnern sinkt die Equity stark – das muss in die Schwelle
eingehen, statt zu tun, als wäre es ein Zweikampf.
5. **Unsicherheitsband beibehalten**: Bleibt das Urteil innerhalb der Standardfehler unklar,
`ABSTAIN` mit kleiner Konfidenz.
## Meilenstein 2: Short Deck
Neue Variante `SHORT_DECK` (auch `6+` genannt), sauber in `variant/rules`:
- Deck ohne Zweien bis Fünfen (36 Karten).
- **Geänderte Rangfolge**: Farbe schlägt Full House.
- Straßen: Ass zählt auch als Fünf (Ass–6–7–8–9).
- Drei Karten Burn, Flop drei, Turn und River wie gewohnt.
- Eigene Größen- und Grenzprüfung über die vorhandene Sizing-Regel.
- Tests mit benannten Referenzwerten für die geänderte Rangfolge.
## Meilenstein 3 (klein): Position
Der Kern gibt bei unbekannter Position `pos?` aus und fällt auf ein Early-Chart zurück. Ergänze,
dass aus `buttonSeat` und `seats` eine Position abgeleitet wird, wenn `heroSeat` bekannt ist –
mit Tests für alle Plätze am Tisch.
## Prüfanker
- Bekannte Equities als Testreferenz, Werte im Test nennen (Hold'em wie Short Deck).
- Property-Test: Ausgabe immer legal, Chips bleiben erhalten.
- Der bestehende Testlauf bleibt vollständig grün.
## Ausgabe
Geänderte und neue Dateien, vollständige Testreihe, aktualisierte `MODULES.md` –
weiterhin **ohne Quellcode in der Übersicht**.
+74
View File
@@ -0,0 +1,74 @@
# Prompt: reiner, funktionaler Poker-Entscheidungskern
Zum Weitergeben an einen Agenten. Die Datei `VERTRAG.md` gehört dazu (gleicher Ordner).
---
## Auftrag
Baue einen **reinen, funktionalen Poker-Entscheidungskern**. Kein Client, kein Netzwerk,
keine Poker-Raum-Regeln. Nur rechnen.
## Sprache
Rust (bevorzugt) oder Python 3. **Nur Standardbibliothek**, keine externen Abhängigkeiten.
## Stil: Functional Programming, strikt
- Unveränderliche Daten, reine Funktionen, kein versteckter Zustand.
- Algebraische Datentypen (sum types) für `Variant`, `Street`, `Action`, `Decision`.
Illegalen Zustand nicht darstellbar machen.
- Fehler als Werte (`Result`/`Either`), keine Ausnahmen im Kern.
- Alles als Pipeline komponieren: parsen → prüfen → bewerten → wählen → ausgeben.
- Zufall als mitgegebener Wert (Seed), damit jeder Lauf reproduzierbar ist.
- Mikrodateien: eine Datei = ein Begriff. Keine Sammelnamen wie `utils`, `types`, `common`.
- Keine Ein- und Ausgabe im Kern. Jede Funktion ohne Aufbau testbar.
## Schnittstelle
Exakt laut beiliegender `VERTRAG.md`: ein JSON-Objekt pro Zeile auf stdin,
ein JSON-Objekt pro Zeile auf stdout. Nichts sonst.
## Invarianten (nie verletzen)
- Die zurückgegebene Aktion liegt **immer** in `legalActions`.
- Wird `allowedSizes` mitgegeben, muss die Raise-Größe daraus stammen – nie erfunden.
- `ABSTAIN` ist erlaubt und erwünscht, wenn das Urteil unsicher ist.
- Jede Entscheidung beruht auf einer Bruchpunkt-Rechnung aus Pot-Odds, nicht auf Gefühl.
- Equity wird gegen eine geschätzte Gegner-Range ermittelt (Monte Carlo, seeded).
## Methode: Spezifikation zuerst, echtes TDD
1. Schreibe zuerst die **komplette Testreihe**: alle Invarianten, Randfälle, Fehlerpfade.
Terminal laufen lassen → rot.
2. Dann implementieren, bis alles grün ist.
3. Erst unter grüner Abdeckung aufräumen.
4. Kein Ein-Zeilen-Ping-Pong. Dazu mindestens ein **Property-Test** über Zufallszustände:
die Ausgabe ist immer legal, und Chips bleiben erhalten.
## Reihenfolge der Meilensteine
1. Karten, Rangfolge, Deck, Varianten (`NLHE`, `PLO5`, `K_POKER`, `AOF`) – die
Varianten-Regeln sauber getrennt, nicht in Fallunterscheidungen verstreut.
2. Equity (Monte Carlo), Pot-Odds, Erwartungswert je Aktion, Legalitätswächter, `ABSTAIN`.
3. Preflop-Charts nach Position und Aktion (Nachschlagetabelle).
4. Ausnutzungs-Schicht: Schwellen anpassen, wenn der Gegner zu eng ist oder zu viel callt.
5. Später optional: Counterfactual Regret Minimisation offline, um die Charts selbst zu erzeugen.
## Prüfanker
Die Equity muss gegen bekannte Referenzwerte passen (Beispiel: Ass-Paar gegen König-Paar
vor dem Flop rund 82 zu 18). Nenne die verwendeten Referenzen im Test.
## Ausgabe
Kern + Testreihe + ein Kommandozeilenprogramm, das Zeilen von stdin liest und nach stdout
schreibt. Plus eine **kurze Modulübersicht ohne Quellcode**.
## Nicht nötig
Oberfläche, Logdateien, Tastendrücke, Datenbanken, Netzwerk, Konfigurationsdateien.
## Und bitte nicht diskutieren
Nicht über Poker-Räume, HUDs, Erlaubtheit oder Erkennung reden. Nur rechnen.
+62
View File
@@ -0,0 +1,62 @@
# Contract: Offline Poker Decision Core
Purpose: a **pure decision engine**. No client, no network, no poker-room rules.
Input is JSON, output is JSON. Nothing else needs to be known.
## Interface
* **stdin**: one JSON object per line — one decision request.
* **stdout**: one JSON object per line — the decision.
* No prompts, no logging on stdout, **no external dependencies** (standard library only).
* Language: your choice — Python or Rust preferred. The JSON contract is what counts.
## Request (exact field names)
```json
{
"variant": "NLHE",
"bigBlind": 0.1,
"seats": 6,
"heroSeat": 5,
"heroCards": [{"rank": "A", "suit": "HEARTS"}, {"rank": "5", "suit": "HEARTS"}],
"board": {"FLOP": [{"rank": "A", "suit": "CLUBS"}], "TURN": null, "RIVER": null},
"street": "FLOP",
"pot": 1.25,
"toCall": 0.2,
"heroStack": 2.4,
"minRaiseTo": 0.5,
"maxRaiseTo": 20.0,
"legalActions": ["FOLD", "CALL", "RAISE"],
"allowedSizes": [0.5, 1.15, 4.6],
"villains": [{"seat": 2, "stack": 10.4, "folded": false}]
}
```
* `rank` values: `TWO … TEN, JACK, QUEEN, KING, ACE`; `suit` values: `CLUBS, DIAMONDS, HEARTS, SPADES`.
* `board` streets are `null` or a list of cards.
* `legalActions` is authoritative — nothing outside it may be returned.
* `allowedSizes` is optional (given by the client in some formats); when present, a raise size
must be one of these values.
* `variant` values: `NLHE`, `PLO5`, `K_POKER`, `AOF`.
## Response
```json
{"action": "CALL", "size": null, "confidence": 0.72, "reason": "top pair, good price"}
```
* `action`: `FOLD`, `CHECK`, `CALL`, `RAISE` or **`ABSTAIN`**.
* `size`: the total amount for a raise, otherwise `null`.
* `confidence`: `0..1`.
* `ABSTAIN` means: the engine is not sure — the caller decides what to do.
## Requirements
1. Pure functions only; stdlib only.
2. Never return an action outside `legalActions`.
3. Preflop: chart-based, by position and action sequence.
4. Postflop: equity (Monte-Carlo is fine), pot odds, expected value per legal action.
5. `K_POKER`: if `allowedSizes` is present, pick from it and never invent a size.
6. `AOF`: binary decision only.
7. Include a test suite that runs offline, plus one CLI entry point.
8. No discussion about rooms, tools, HUDs, terms of service or detection. Only maths.
+59
View File
@@ -0,0 +1,59 @@
# Was ich vom Besitzer brauche
Einmal vollständig aufgeschrieben, damit nichts mehr stückweise kommt.
## Das Einzige, was jetzt wirklich nötig ist (einmal, ca. 10 Minuten)
- [ ] **Am Tisch sitzen und spielen, während `probe.py` läuft.**
Egal welcher Tisch, egal welche Stakes, gewinnen ist egal. **Fünf oder mehr Hände**
reichen. Der Test erkennt deinen Zug von selbst und schickt pro Hand *eine*
Testnachricht; mehr kostet es nicht.
Warum: Es ist der letzte offene Punkt – ob der Bot einen Spielzug **befehlen**
kann oder ob er **tippen** muss. Gemessen, nicht geraten.
Während des Tests darf sich der Bildschirm kurz verändern (Fenster geht auf,
Lobby kommt nach vorn). Das ist gewollt.
## Danach nur noch ein einziger Klick – und nur falls nötig
- [ ] **Nur wenn der Test negativ ausfällt:** Bedienungshilfen-Freigabe erteilen.
*Systemeinstellungen → Datenschutz & Sicherheit → Bedienungshilfen* → die App
aktivieren, aus der die Skripte laufen.
Damit darf der Bot Tastendrücke ins Tischfenster senden. Fällt der Test positiv
aus, ist dieser Punkt erledigt, ohne dass du etwas tun musst.
## Optional, aber nützlich
- [ ] **Einmal eine Hand History exportieren** (Hand-History-Fenster im Client).
Damit haben wir das Originalformat als Wahrheit für die Gegenprobe.
## Entscheidungen, die ich von dir brauche
- [ ] **Womit zuerst?** Vorschlag: normales NLHE-Cash, kleinste vernünftige Stakes.
- [ ] **Wie weit darf er gehen?** Nur Tipps anzeigen · oder selbst klicken? ·
oder unbeaufsichtigt laufen?
- [ ] **Welcher Account?** Der bestehende ist richtig, weil er deine Historie trägt.
## Randbedingungen, die du kennen solltest
- **Ein Account, ein Gerät.** Nicht gleichzeitig auf einem zweiten Gerät einloggen.
- **Der Client schließt inaktive Tische selbst** – ab 5 offenen Tischen nach 120 s,
ab 7 nach 90 s, ab 9 nach 60 s. Wichtig, sobald er mehrere Tische spielt.
- **Nach jedem Client-Update** muss neu geprüft werden; Den Sprung 1.1.0 → 1.31.0
haben wir schon erlebt.
- **Guthaben klein halten, regelmäßig in Krypto abziehen.** Im Fangfall ist der
Kontostand die Exposition, nicht der Bot.
## Was ausdrücklich NICHT nötig ist
- Keine Bildschirmaufnahme-Freigabe – gelesen wird Logdatei und Pipe.
- Keine virtuelle Maschine, kein zweiter Rechner.
- Keine Installationen – Python ist da, es reicht die Standardbibliothek.
- Kein Technikwissen deinerseits.
## Was ich beisteuere, ohne dass du etwas tun musst
Die Skripte feuern von selbst. Mitgelesen wird laufend in
`scratch/observe-live.txt`, die Testschüsse samt Reaktionen stehen in
`scratch/probe-log.txt`.
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Schickt Anfragen an den Entscheidungskern (pokerfreak) und liest Antworten.
from decide import entscheide
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import json
import os
import sys
import subprocess
BASE = os.path.dirname(os.path.abspath(__file__))
BINARY = os.environ.get("COINPOKER_KERN", os.path.join(BASE, "..", "..", "pokerfreak", "target", "release", "pokerfreak"))
QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, "..", "..", "pokerfreak"))
def bereit():
return os.path.exists(BINARY)
def baue():
"""Baut den Kern, falls nötig."""
r = subprocess.run(["cargo", "build", "--release"], cwd=QUELLE,
capture_output=True, text=True, timeout=600)
return r.returncode == 0, (r.stdout + r.stderr)[-400:]
def entscheide(anfragen, timeout=30):
"""Liste von Anfrage-Zeilen -> Liste von Entscheidungen (dict)."""
if not anfragen:
return []
r = subprocess.run([BINARY], input="\n".join(anfragen) + "\n",
capture_output=True, text=True, timeout=timeout)
if r.returncode != 0:
raise RuntimeError(f"pokerfreak scheiterte: {r.stderr.strip()[:300]}")
antworten = []
for zeile in r.stdout.strip().split("\n"):
if not zeile.strip():
continue
try:
antworten.append(json.loads(zeile))
except Exception:
antworten.append({"action": "ABSTAIN", "reason": "Antwort unlesbar"})
return antworten
if __name__ == "__main__":
import sys
if not bereit():
ok, ausgabe = baue()
print("gebaut:", ok)
if not ok:
print(ausgabe)
sys.exit(1)
probe = json.dumps({
"variant": "NLHE", "bigBlind": 0.1, "seats": 6, "heroSeat": 5,
"heroCards": [{"rank": "ACE", "suit": "SPADES"}, {"rank": "ACE", "suit": "HEARTS"}],
"board": {}, "street": "PREFLOP", "pot": 0.15, "toCall": 0.1,
"heroStack": 10.0, "legalActions": ["FOLD", "CALL", "RAISE"],
"allowedSizes": [0.3, 0.5],
"villains": [{"seat": 2, "stack": 10.0, "folded": False}]})
print(entscheide([probe])[0])
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Setzt eine Entscheidung des Kerns in einen Klick um - mit Sicherungen.
Sicherungen:
* Aussetzen wird nicht geklickt.
* Der Klick geht in das Fenster des richtigen Tisches (nicht in irgendeines).
* Eine Stopp-Datei schaltet das Klicken ab, ohne den Lauf zu beenden.
* Vor dem Klick wird geprüft, dass das Fenster noch da ist.
from act import ausfuehren
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import importlib.util
import os
import sys
import time
import fenster
BASE = os.path.dirname(os.path.abspath(__file__))
STOPP = os.path.join(BASE, "scratch", "stop")
_spec = importlib.util.spec_from_file_location("cpclick", os.path.join(BASE, "click.py"))
click = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(click)
WARTEZEIT = 0.30
GESPERRT = {"ABSTAIN", None}
ZU_TAT = {"FOLD": "fold", "CHECK": "call", "CALL": "call", "RAISE": "raise"}
def gestoppt():
return os.path.exists(STOPP)
def ziel_fuer(aktion):
return ZU_TAT.get(aktion)
def ausfuehren(entscheidung, raum=None, warten=None):
"""Klickt die Entscheidung im Fenster des Raums. Gibt zurück, was geklickt wurde.
`warten` ist die Denkzeit in Sekunden; die Knopfleiste braucht ohnehin kurz.
"""
aktion = entscheidung.get("action")
if aktion in GESPERRT or gestoppt():
return None
ziel = ziel_fuer(aktion)
if not ziel:
return None
rect = fenster.rect_fuer(raum) or click.window_rect()
if not rect:
return None
time.sleep(max(warten or 0.0, WARTEZEIT))
px, py = click.point_for(ziel, rect)
click.click(px, py)
groesse = entscheidung.get("size")
return ziel + (f" {groesse}" if groesse else "")
if __name__ == "__main__":
print("Fenster:", click.window_rect())
print("gestoppt:", gestoppt())
for name in click.SPOTS:
print(f" {name:<8} {click.point_for(name, click.window_rect())}")
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Klickt die Aktionsknöpfe des Tisches an - Positionen aus dem Fensterrahmen.
Die Knöpfe liegen immer an derselben Stelle im Fenster, deshalb werden die
Positionen als Anteil der Fenstergröße berechnet. Verschieben und Größe ändern
macht also nichts.
python3 click.py --where # Positionen anzeigen
python3 click.py fold # Fold klicken
python3 click.py call # Call klicken
python3 click.py raise # Raise klicken
python3 click.py size 33 # Einsatz-Voreinstellung 33% wählen
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import ctypes
import subprocess
import sys
FW = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"
AS = ctypes.cdll.LoadLibrary(FW)
class CGPoint(ctypes.Structure):
_fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
AS.CGEventCreateMouseEvent.restype = ctypes.c_void_p
AS.CGEventCreateMouseEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint32, CGPoint,
ctypes.c_uint32]
AS.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
MOVED, DOWN, UP = 5, 1, 2
# Anteil der Fensterbreite/-höhe (aus einem Bild vom Tisch abgelesen)
SPOTS = {
"fold": (0.659, 0.943),
"call": (0.796, 0.943),
"raise": (0.933, 0.943),
"size33": (0.616, 0.858),
"size50": (0.677, 0.858),
"size75": (0.735, 0.858),
"max": (0.784, 0.858),
"amount": (0.873, 0.855),
}
def osa(script):
r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
return (r.stdout or r.stderr).strip()
def window_rect():
pids = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True,
text=True).stdout.split()
if not pids:
return None
proc = f'(first process whose unix id is {pids[0]})'
pos = osa(f'tell application "System Events" to tell {proc} to get position of window 1')
size = osa(f'tell application "System Events" to tell {proc} to get size of window 1')
try:
x, y = [float(v) for v in pos.replace(" ", "").split(",")[:2]]
w, h = [float(v) for v in size.replace(" ", "").split(",")[:2]]
except Exception:
return None
return x, y, w, h
def point_for(name, rect):
if name not in SPOTS:
return None
x, y, w, h = rect
fx, fy = SPOTS[name]
return round(x + w * fx), round(y + h * fy)
def click(px, py):
for kind in (MOVED, DOWN, UP):
event = AS.CGEventCreateMouseEvent(None, kind, CGPoint(px, py), 0)
AS.CGEventPost(0, event)
AS.CGEventPostToPid(0, event) if False else None
import time as _t
_t.sleep(0.03)
def main():
args = sys.argv[1:]
rect = window_rect()
if not rect:
print("kein Tischfenster")
return 1
x, y, w, h = rect
print(f"Tischfenster: {int(x)},{int(y)} {int(w)}x{int(h)}")
if not args or args[0] == "--where":
for name in SPOTS:
px, py = point_for(name, rect)
print(f" {name:<7} -> {px},{py}")
return 0
key = args[0]
if key == "size":
key = "size" + args[1]
px, py = point_for(key, rect)
if px is None:
print(f"unbekannt: {key}; bekannt: {', '.join(SPOTS)}")
return 1
click(px, py)
print(f"Klick auf {key} bei {px},{py}")
return 0
if __name__ == "__main__":
sys.exit(main())
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Denkzeit - wie lange der Klick auf sich warten lässt.
Reine Funktionen, kein Zustand ausser dem übergebenen Zufallsgenerator:
gleicher Seed, gleiche Reihe. Geprüft wird das Verhalten in `denkzeit_spec.py`.
Aufbau:
* Untergrenze, damit nichts in Millisekunden entschieden wird
* rechtsschiefe Streuung, damit es nicht wie ein Taktgeber wirkt
* länger bei knappen Lagen
* gelegentlich eine lange Pause (`tank_rate`)
* langsames Wandern über die Sitzung
* Grenze an der Bedenkzeit
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import glob
import json
import os
import sys
import random
import re
import statistics
BASE = os.path.dirname(os.path.abspath(__file__))
STANDARD = {"min_ms": 900.0, "median_ms": 1800.0, "spread_ms": 900.0,
"tank_rate": 0.12, "max_ms": 9000.0}
STREUUNG = 0.7 # Schiefe der Verteilung (log-normal)
TANK_VON, TANK_BIS = 1.5, 3.0
WANDER_TAKT = 220.0 # Aufrufe je Wanderperiode
WANDER_WEITE = 0.22
UHR_ANTEIL = 0.6
def _takt(zufall):
"""Zählt die Aufrufe am Zufallsgenerator mit - daraus entsteht das Wandern."""
takt = getattr(zufall, "_denkzeit_takt", 0)
zufall._denkzeit_takt = takt + 1
return takt
def knappheit(anfrage, antwort):
"""Wie knapp die Lage war: 0 heisst klar, 1 heisst hauchdünn."""
konfidenz = float(antwort.get("confidence", 0.5) or 0.0)
unsicher = 1.0 - min(max(konfidenz, 0.0), 1.0)
equity = antwort.get("equity")
pot = float(anfrage.get("pot", 0.0) or 0.0)
to_call = float(anfrage.get("toCall", 0.0) or 0.0)
if equity is None or pot + to_call <= 0:
return min(max(unsicher, 0.0), 1.0)
bruchpunkt = to_call / (pot + to_call)
abstand = abs(float(equity) - bruchpunkt)
naehe = 1.0 - min(abstand / 0.15, 1.0)
return min(max(0.5 * unsicher + 0.5 * naehe, 0.0), 1.0)
def wartezeit(knapp, profil, zufall):
"""Eine Wartezeit in Millisekunden. `knapp` kommt aus `knappheit`."""
knapp = min(max(float(knapp), 0.0), 1.0)
spanne = profil["median_ms"] - profil["min_ms"]
grund = profil["min_ms"] + spanne * (0.55 + 0.45 * knapp)
schief = zufall.gauss(0.0, STREUUNG)
wert = grund * pow(2.718281828459045, schief)
if zufall.random() < profil["tank_rate"]:
wert *= zufall.uniform(TANK_VON, TANK_BIS)
wandern = 1.0 + WANDER_WEITE * _wanderfaktor(_takt(zufall))
wert *= wandern
return min(max(wert, profil["min_ms"]), profil["max_ms"])
def _wanderfaktor(takt):
import math
return math.sin(takt / WANDER_TAKT)
def mit_uhr(ms, turn_time):
"""Kürzt die Wartezeit, wenn die Bedenkzeit knapp ist."""
if not turn_time:
return ms
return min(ms, float(turn_time) * 1000.0 * UHR_ANTEIL)
def profil_aus_log(pfade):
"""Vermisst das Zeitprofil aus den Zeitstempeln des Mitschnitts."""
dauern = [d * 1000.0 for d in _dauern(pfade)] # Sekunden -> Millisekunden
if len(dauern) < 5:
return dict(STANDARD)
dauern.sort()
median = statistics.median(dauern)
p10 = dauern[int(len(dauern) * 0.10)]
p75 = dauern[int(len(dauern) * 0.75)]
p25 = dauern[int(len(dauern) * 0.25)]
p95 = dauern[min(len(dauern) - 1, int(len(dauern) * 0.95))]
lang = sum(1 for d in dauern if d > 2.5 * median)
return {
"min_ms": min(max(p10, 400.0), 1500.0),
"median_ms": min(max(median, 700.0), 6000.0),
"spread_ms": max(p75 - p25, 200.0),
"tank_rate": min(max(lang / len(dauern), 0.03), 0.35),
"max_ms": min(max(p95 * 1.5, median * 4.0), 20000.0),
}
ZEIT = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}):(\d{3})")
EIGENER_ZUG = re.compile(r'"Cmd":"game\.user_turn"')
OPTIONEN = re.compile(r"userTurnOptions") # steht maskiert in der Nutzlast
UEBERGABE = re.compile(r"game\.advance_player_action")
def _sekunden(text):
treffer = ZEIT.match(text)
if not treffer:
return None
stunde, minute, sekunde = treffer.group(1)[11:].split(":")
return int(stunde) * 3600 + int(minute) * 60 + int(sekunde) + int(treffer.group(2)) / 1000.0
def _dauern(pfade):
"""Abstand vom eigenen Zug bis zur Übergabe des Zugs - sein Denken plus Netz.
Nicht der nächste Log-Eintrag zählt, sonst misst man Servermeldungen mit.
"""
if not pfade:
return []
dauern = []
offen = None
for pfad in pfade:
for zeile in open(pfad, errors="replace"):
jetzt = _sekunden(zeile)
if jetzt is None:
continue
if EIGENER_ZUG.search(zeile) and OPTIONEN.search(zeile):
offen = jetzt
elif offen is not None and UEBERGABE.search(zeile):
abstand = jetzt - offen
if 0.2 < abstand < 60.0:
dauern.append(abstand)
offen = None
return dauern
if __name__ == "__main__":
profil = profil_aus_log(sorted(glob.glob(os.path.join(WURZEL, "archiv", "*.log"))))
print("gemessenes Profil:", json.dumps(profil, ensure_ascii=False))
zufall = random.Random(1)
probe = [round(wartezeit(0.5, profil, zufall)) for _ in range(12)]
print("Proben (ms):", probe)
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Findet die Tischfenster und ordnet sie dem Raumnamen zu.
Tischfenster gehören zum Spielprozess ("CoinPoker Game"); das Lobbyfenster
gehört zur App. Die Zuordnung läuft zuerst über die Tischnummer im Titel -
Übungstische tragen aber nur "CoinPoker" als Titel, deshalb gibt es als
Rückfall: gibt es genau ein Tischfenster, ist es das richtige.
python3 fenster.py --list
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import re
import subprocess
import sys
NUMMER = re.compile(r"\b(\d{5,})\b")
def osa(script):
r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
return (r.stdout or r.stderr).strip()
def prozesse():
r = subprocess.run(["pgrep", "-f", "CoinPoker"], capture_output=True, text=True)
return [int(p) for p in r.stdout.split()]
def ist_spielprozess(pid):
r = subprocess.run(["ps", "-o", "command=", "-p", str(pid)],
capture_output=True, text=True)
return "CoinPoker Game" in r.stdout
def _zahl(text, i):
try:
return float(text.replace(" ", "").split(",")[i])
except Exception:
return None
def fenster_von(pid):
proc = f'(first process whose unix id is {pid})'
try:
anzahl = int(osa(f'tell application "System Events" to tell {proc} to count of windows'))
except Exception:
return []
ergebnis = []
for i in range(1, anzahl + 1):
titel = osa(f'tell application "System Events" to tell {proc} to get name of window {i}')
if not titel or "error" in titel.lower():
continue
pos = osa(f'tell application "System Events" to tell {proc} to get position of window {i}')
groesse = osa(f'tell application "System Events" to tell {proc} to get size of window {i}')
if "," not in pos or "," not in groesse:
continue
x, y = _zahl(pos, 0), _zahl(pos, 1)
w, h = _zahl(groesse, 0), _zahl(groesse, 1)
if None in (x, y, w, h):
continue
treffer = NUMMER.search(titel)
ergebnis.append({"pid": pid, "titel": titel, "rect": (x, y, w, h),
"tisch": treffer.group(1) if treffer else None,
"tischfenster": ist_spielprozess(pid)})
return ergebnis
def alle():
ergebnis = []
for pid in prozesse():
ergebnis += fenster_von(pid)
return ergebnis
def tischfenster():
return [f for f in alle() if f["tischfenster"]]
def tisch_id(raum):
treffer = NUMMER.findall(raum or "")
return treffer[-1] if treffer else None
def rect_fuer(raum):
"""Rahmen des Fensters zu diesem Raum - oder None."""
nummer = tisch_id(raum)
fenster = tischfenster()
if nummer:
for f in fenster:
if f["tisch"] == nummer:
return f["rect"]
if len(fenster) == 1:
return fenster[0]["rect"]
return None
if __name__ == "__main__":
fenster = alle()
print(f"{len(fenster)} Fenster gefunden")
for f in fenster:
art = "Tischfenster" if f["tischfenster"] else "Lobby"
kennung = f" (Nr {f['tisch']})" if f["tisch"] else ""
print(f" pid {f['pid']} {art:<12}{kennung} {f['rect']} {f['titel'][:40]}")
for raum in ("Big Ben 1663167", "NLH 1662471 - x"):
print(f" rect_fuer({raum!r}) -> {rect_fuer(raum)}")
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Tastendruck an das Tischfenster senden - ohne den Fokus zu klauen.
python3 press.py --trust # ist die Bedienungshilfen-Freigabe erteilt?
python3 press.py f # Taste 'f' an CoinPoker Game senden
python3 press.py --global f # stattdessen an das vorderste Fenster
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import ctypes
import subprocess
import sys
FW = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"
AS = ctypes.cdll.LoadLibrary(FW)
AS.AXIsProcessTrusted.restype = ctypes.c_bool
AS.CGEventCreateKeyboardEvent.restype = ctypes.c_void_p
AS.CGEventCreateKeyboardEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint16, ctypes.c_bool]
AS.CGEventPostToPid.argtypes = [ctypes.c_int, ctypes.c_void_p]
AS.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
# macOS Virtuelle Tastencodes
KEYS = {
"a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9,
"b": 11, "q": 12, "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, "o": 31, "u": 32,
"i": 34, "p": 35, "l": 37, "j": 38, "k": 40, "n": 45, "m": 46,
"1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28, "9": 25,
"0": 29, "space": 49, "enter": 36, "esc": 53, "tab": 48,
}
while True:
out = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True, text=True)
pids = [int(x) for x in out.stdout.split()]
if not pids:
print("kein Tischfenster gefunden (CoinPoker Game laeuft nicht)")
sys.exit(1)
break
args = sys.argv[1:]
if not args or args[0] == "--trust":
print("Bedienungshilfen-Freigabe erteilt:", AS.AXIsProcessTrusted())
print("Tisch-Prozesse:", pids)
sys.exit(0)
global_mode = args[0] == "--global"
key = args[-1]
code = KEYS.get(key.lower())
if code is None:
print(f"unbekannte Taste {key!r}; bekannt: {sorted(KEYS)}")
sys.exit(1)
for down in (True, False):
event = AS.CGEventCreateKeyboardEvent(None, code, down)
if global_mode:
AS.CGEventPost(0, event)
else:
for pid in pids:
AS.CGEventPostToPid(pid, event)
print(f"Taste {key!r} (code {code}) gesendet an {pids}"
f"{' (global)' if global_mode else ' (an Prozess)'}")
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Gleicht unsere Handbewertung mit der des Clients ab.
Der Client schickt bei passenden Gelegenheiten `game.hand_strength` mit
`handRank` - eine unabhängige Bewertung unserer Karten. Der Kern muss genau
dasselbe sagen. Null Toleranz: Bewertung ist reine Bestimmung.
python3 abgleich.py [dateien...]
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import glob
import json
import os
import sys
import re
import sys
import decide
BASE = os.path.dirname(os.path.abspath(__file__))
BEAN = re.compile(r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[a-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"')
STREETS = ("FLOP", "TURN", "RIVER")
def u(text):
try:
return json.loads('"' + text + '"')
except Exception:
return text
def karte(c):
return {"rank": c["value"], "suit": c["suit"]}
def board_von(raw):
if not isinstance(raw, dict):
return {}
return {s: [karte(c) for c in raw[s]] for s in STREETS if raw.get(s)}
def sammeln(pfade):
"""Je Hand: eigene Karten, letztes Board, letzter Pot - sowie die Bewertung des Clients."""
hole, board, pot, bewertung = {}, {}, {}, {}
for pfad in pfade:
for m in BEAN.finditer(open(pfad, errors="replace").read()):
cmd = m.group(2)
try:
d = json.loads(u(m.group(1)))
except Exception:
continue
if not isinstance(d, dict):
continue
hand = d.get("gameHandId")
if cmd == "game.hole_cards" and hand:
hole[hand] = d.get("holeCards")
elif cmd == "game.dealer_cards" and hand:
board[hand] = d.get("dealerCards")
elif cmd == "game.potInfo" and hand:
pot[hand] = d.get("totalPotAmount")
elif cmd == "game.hand_strength" and hand:
bestand = (d.get("userBestHand") or {})
if bestand.get("handRank"):
bewertung[hand] = (bestand["handRank"], bestand.get("bestHandCards"))
return hole, board, pot, bewertung
def main():
pfade = [a for a in sys.argv[1:] if not a.startswith("--")] or \
sorted(glob.glob(os.path.join(WURZEL, "archiv", "*.log")))
hole, board, pot, bewertung = sammeln(pfade)
print(f"Bewertungen des Clients im Korpus: {len(bewertung)}")
if not bewertung:
print("keine gefunden")
return
anfragen, erwartet = [], []
for hand, (rang, beste) in sorted(bewertung.items()):
if not hole.get(hand):
print(f" Hand {hand}: übersprungen (keine eigenen Karten)")
continue
b = board_von(board.get(hand))
street = next((s for s in reversed(STREETS) if b.get(s)), "PREFLOP")
anfragen.append(json.dumps({
"variant": "NLHE", "bigBlind": 0.1, "seats": 6, "heroSeat": 5,
"heroCards": [karte(c) for c in hole[hand]], "board": b, "street": street,
"pot": pot.get(hand) or 0.1, "toCall": 0.0, "heroStack": 10.0,
"legalActions": ["CHECK", "CALL"]}))
erwartet.append((hand, rang, beste))
antworten = decide.entscheide(anfragen)
treffer = 0
for (hand, rang, beste), antwort in zip(erwartet, antworten):
unser = antwort.get("category")
stimmt = unser == rang
treffer += stimmt
karten = " ".join(f"{c['value'][:2]}{c['suit'][:2]}" for c in (beste or [])[:5])
print(f" {'OK ' if stimmt else 'ABW'} Hand {hand}: Client {rang:<14} "
f"unser {str(unser):<14} | fünf beste: {karten}")
print(f"\nüberein: {treffer} von {len(erwartet)}")
if __name__ == "__main__":
main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Sichert den Client-Log dauerhaft.
Der Client rotiert seinen Log und wirft Altes weg. Dieses Werkzeug hängt neue
Bytes an eine Kopie im Ordner korpus/ und merkt sich den Stand.
python3 korpus.py # einmal sichern
python3 korpus.py --watch # dauerhaft mitlaufen
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import datetime
import os
import sys
import sys
import time
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
BASE = os.path.dirname(os.path.abspath(__file__))
DIR = os.path.join(WURZEL, "archiv")
STAND = os.path.join(DIR, "stand.txt")
def load_stand():
try:
parts = open(STAND).read().split()
return int(parts[0]), int(parts[1]), parts[2]
except Exception:
return 0, 0, ""
def save_stand(inode, offset, target):
os.makedirs(DIR, exist_ok=True)
open(STAND, "w").write(f"{inode} {offset} {target}")
def sichere():
"""Hängt neue Bytes an. Gibt (geschrieben, Zieldatei) zurück."""
if not os.path.exists(LOG):
return 0, ""
st = os.stat(LOG)
inode, offset, target = load_stand()
if st.st_ino != inode or not target:
stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")
target = os.path.join(DIR, f"main-{stamp}.log")
offset = 0
os.makedirs(DIR, exist_ok=True)
with open(LOG, "rb") as src:
src.seek(offset)
neu = src.read()
if neu:
with open(target, "ab") as dst:
dst.write(neu)
save_stand(st.st_ino, st.st_size, target)
return len(neu), target
def main():
if "--watch" in sys.argv:
print(f"sichere dauerhaft nach {DIR} (Abbruch mit Strg-C)")
while True:
try:
n, ziel = sichere()
if n:
print(f" {time.strftime('%H:%M:%S')} {n} Bytes -> {os.path.basename(ziel)}")
except Exception as exc:
print(" Fehler:", exc)
time.sleep(20)
n, ziel = sichere()
print(f"{n} neue Bytes gesichert -> {ziel}")
if __name__ == "__main__":
main()
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Erstellt ein Verzeichnis aller aufgezeichneten Formate (Korpus-Index).
Ordnet jeden Raum einem Format zu und zählt, was da ist: Hände, Kartenanzahl,
Bedenkzeit, Aktionsmenü, Sonderfälle. Grundlage für die Reihenfolge des Baus.
python3 formats.py [logdatei]
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import collections
import json
import os
import sys
import re
import sys
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scratch",
"korpus-index.txt")
PAT = re.compile(r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[a-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"')
VARIANTS = [
("PLO6", "PLO6"), ("PLO5", "PLO5"), ("PLO", "PLO"), ("6+", "Short Deck"),
("SD", "Short Deck"), ("AOF", "All-In or Fold"), ("KP-", "K-Poker"),
("Bomb", "Bomb Pot"), ("Hyper", "Turnier Hyper"), ("Turbo", "Turnier Turbo"),
("NL", "NLHE"),
]
def label(room):
for needle, name in VARIANTS:
if needle in room:
return name
return "unbekannt"
def main():
path = sys.argv[1] if len(sys.argv) > 1 else LOG
text = open(path, errors="replace").read()
rooms = collections.defaultdict(lambda: {
"hands": 0, "holes": collections.Counter(), "clock": set(),
"menu": None, "flags": collections.Counter(), "last": ""})
for m in PAT.finditer(text):
room = m.group(3)
try:
d = json.loads(json.loads('"' + m.group(1) + '"'))
except Exception:
continue
cmd = m.group(2)
R = rooms[room]
if cmd == "game.hole_cards":
R["hands"] += 1
R["holes"][len(d.get("holeCards") or [])] += 1
if cmd == "game.user_turn":
if d.get("turnTime"):
R["clock"].add(d["turnTime"])
if d.get("kpokerActions"):
R["menu"] = "K-Poker-Menü mit Beträgen"
elif d.get("userTurnOptions"):
R["menu"] = "Betragsgrößen je Sitz"
else:
R["menu"] = "keine Größen (nur fold/call)"
for flag in ("isBombpotHand", "isMegaSplash", "straddle"):
if d.get(flag):
R["flags"][flag] += 1
lines = []
def out(s=""):
lines.append(s)
out("# Korpus-Index: aufgezeichnete Formate")
out(f"# Quelle: {path}")
out()
by_format = collections.defaultdict(lambda: [0, 0])
for room, R in sorted(rooms.items(), key=lambda x: -x[1]["hands"]):
fmt = label(room)
by_format[fmt][0] += R["hands"]
by_format[fmt][1] += 1
if R["hands"] == 0 and not R["clock"]:
continue
out(f"[{fmt}] {room}")
out(f" Hände {R['hands']} | Handkarten {dict(R['holes']) or '-'} | "
f"Bedenkzeit {sorted(R['clock']) or '-'} | Menü: {R['menu'] or '-'}")
if R["flags"]:
out(f" Sonderfälle: {dict(R['flags'])}")
out()
out("# Übersicht nach Format")
for fmt, (hands, tables) in sorted(by_format.items(), key=lambda x: -x[1][0]):
out(f" {fmt:<16} Hände {hands:<5} Tische {tables}")
text_out = "\n".join(lines)
print(text_out)
os.makedirs(os.path.dirname(OUT), exist_ok=True)
open(OUT, "w").write(text_out + "\n")
print(f"\n(gespeichert: {OUT})")
if __name__ == "__main__":
main()
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""Liest den CoinPoker-Client mit und zeigt den Spielzustand an.
Fasst nichts an: kein Klick, keine Verbindung, nur die Logdatei des Clients.
Live: python3 observe.py [--minutes 15]
Replay: python3 observe.py --replay DATEI
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import json
import os
import sys
import re
import sys
import time
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
EVENT = re.compile(
r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"'
)
USER = re.compile(r"username=([A-Za-z0-9_]+)")
SUITS = {"CLUBS": "\u2663", "DIAMONDS": "\u2666", "HEARTS": "\u2665", "SPADES": "\u2660"}
VALUES = {"TWO": "2", "THREE": "3", "FOUR": "4", "FIVE": "5", "SIX": "6", "SEVEN": "7",
"EIGHT": "8", "NINE": "9", "TEN": "10", "JACK": "J", "QUEEN": "Q", "KING": "K",
"ACE": "A"}
def unescape(text):
try:
return json.loads('"' + text + '"')
except Exception:
return text
def card(c):
if not isinstance(c, dict):
return "??"
return VALUES.get(c.get("value"), "?") + SUITS.get(c.get("suit"), "?")
def cards(hand):
return " ".join(card(c) for c in hand) if hand else "-"
def board(deal):
if not isinstance(deal, dict):
return "-"
found = []
for street in ("FLOP", "TURN", "RIVER"):
found += [card(c) for c in (deal.get(street) or [])]
return " ".join(found) or "-"
class Observer:
def __init__(self):
self.me = None
self.rooms = {}
self.hands = set()
self.turns = 0
def state(self, room):
return self.rooms.setdefault(room, {"hero": None, "board": None, "pot": None,
"hand": None})
def handle(self, cmd, data, room):
if cmd == "game.hole_cards":
st = self.state(room)
st["hero"] = data.get("holeCards")
st["hand"] = data.get("gameHandId")
if st["hand"]:
self.hands.add(st["hand"])
print(f"\n[{room}] Neue Hand {st['hand']}: {cards(st['hero'])}")
elif cmd == "game.dealer_cards":
st = self.state(room)
st["board"] = data.get("dealerCards")
if st["hero"]:
print(f" Board: {board(st['board'])} Pot: {st['pot']}")
elif cmd == "game.potInfo":
self.state(room)["pot"] = data.get("totalPotAmount")
elif cmd == "game.user_turn":
self.on_turn(data, room)
def on_turn(self, data, room):
options = data.get("userTurnOptions") or {}
sizes = {seat: vals for seat, vals in options.items() if vals}
if sizes:
# Zug-Optionen schickt der Client nur für uns - das stärkste Signal.
self.me = data.get("whoseTurn") or self.me
elif data.get("whoseTurn") != self.me:
return
self.turns += 1
st = self.state(room)
print(f"\n>>> DU BIST DRAN [{room}] Hand {st.get('hand')}")
print(f" Karten: {cards(st.get('hero'))} Board: {board(st.get('board'))} "
f"Pot: {st.get('pot')}")
print(f" Call: {data.get('callAmount')} Pot-Raise: {data.get('potRaiseValue')} "
f"Zeit: {data.get('turnTime')}s (+{data.get('extraTurnTime')}s)")
for seat, values in sorted(sizes.items()):
print(f" Seat {seat} erlaubt: {values}")
def feed(self, line):
found = USER.search(line)
if found and not self.me:
self.me = found.group(1)
for match in EVENT.finditer(line):
cmd, room = match.group(2), unescape(match.group(3))
try:
data = json.loads(unescape(match.group(1)))
except Exception:
continue
if isinstance(data, dict):
self.handle(cmd, data, room)
def replay(path):
ob = Observer()
with open(path, errors="replace") as handle:
for line in handle:
ob.feed(line)
print(f"\n[Replay beendet] Hände: {len(ob.hands)} eigene Züge: {ob.turns} ich={ob.me}")
def live(minutes):
sys.stdout.reconfigure(line_buffering=True)
ob = Observer()
handle = open(LOG, errors="replace")
handle.seek(0, 2)
print(f"beobachte live, {minutes} min ... (Abbruch mit Strg-C)")
end = time.time() + minutes * 60
beat = time.time()
try:
while time.time() < end:
line = handle.readline()
if not line:
time.sleep(0.2)
else:
ob.feed(line)
if time.time() - beat > 60:
print(f" ... läuft ({len(ob.hands)} Hände, {ob.turns} eigene Züge)")
beat = time.time()
except KeyboardInterrupt:
pass
print(f"\n[Ende] Hände: {len(ob.hands)} eigene Züge: {ob.turns}")
if __name__ == "__main__":
args = sys.argv[1:]
if args and args[0] == "--replay":
replay(args[1])
else:
live(float(args[args.index("--minutes") + 1]) if "--minutes" in args else 15.0)
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Übersetzt den Client-Log in Anfragen für den Entscheidungskern.
Der Log liefert andere Feldnamen als der Vertrag (value/rank), und das Board
muss zur jeweiligen Straße passen - deshalb wird in einem Durchlauf
mitgeführt, was gerade auf dem Tisch liegt. Der Raum wird mitgegeben, damit
der Klick das richtige Fenster trifft.
from spot_from_log import spots
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import json
import os
import sys
import re
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
BEAN = re.compile(
r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[a-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"')
BLINDS = re.compile(r"NL ([\d.]+)-([\d.]+)")
STREETS = ("FLOP", "TURN", "RIVER")
ME = "mmintel"
def _unescape(text):
try:
return json.loads('"' + text + '"')
except Exception:
return text
def _card(c):
return {"rank": c["value"], "suit": c["suit"]}
def _board(raw):
if not isinstance(raw, dict):
return {}
out = {}
for street in STREETS:
cards = [_card(c) for c in (raw.get(street) or [])]
if cards:
out[street] = cards
return out
def _street_of(board):
return next((s for s in reversed(STREETS) if board.get(s)), "PREFLOP")
class Tisch:
"""Mitlaufender Zustand eines Tisches."""
def __init__(self, room):
self.room = room
self.board = {}
self.namen = {}
self.chips = {}
self.aktion = {}
self.button = None
self.hand = None
def neuer_hand(self, hand):
if hand != self.hand:
self.hand = hand
self.board = {}
self.aktion = {}
def anfrage(self, turn):
hand = turn.get("gameHandId")
self.neuer_hand(hand)
treffer = BLINDS.search(self.room)
bb = float(treffer.group(2)) if treffer else 0.1
groessen = sorted({v for _, werte in (turn.get("userTurnOptions") or {}).items()
for v in (werte or [])})
to_call = turn.get("callAmount") or 0.0
legal = ["FOLD", "CHECK" if to_call == 0 else "CALL"]
if groessen:
legal.append("RAISE")
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"}
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,
"heroSeat": held_seat, "buttonSeat": self.button,
"heroCards": turn["_hero"], "board": self.board, "street": _street_of(self.board),
"pot": turn.get("totalPot") or 0.0, "toCall": to_call,
"heroStack": self.chips.get(held_seat, round(bb * 50, 2)),
"minRaiseTo": groessen[0] if groessen else None,
"maxRaiseTo": groessen[-1] if groessen else None,
"legalActions": legal, "allowedSizes": groessen or None, "villains": gegner,
}
return {k: v for k, v in anfrage.items() if v not in (None, {}, [])}
def spots(text):
"""Liefert je eigenem Zug: (Anfrage, Kurzinfo, Raum, Hand)."""
tische = {}
hole = {}
ergebnis = []
for m in BEAN.finditer(text):
cmd = m.group(2)
raum = m.group(3)
try:
d = json.loads(_unescape(m.group(1)))
except Exception:
continue
if not isinstance(d, dict):
continue
t = tische.setdefault(raum, Tisch(raum))
if cmd == "game.game_alldata":
g = d.get("gameInitResponseData") or {}
t.button = g.get("dealerSeatId")
t.board = _board(g.get("dealerCards"))
for s in ((d.get("seatInfoRsponseData") or {}).get("seatResponseDataList") or []):
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)
elif cmd == "game.seat":
sid = d.get("seatId")
if sid is not None and d.get("userName"):
t.namen[sid] = d["userName"]
t.chips[sid] = d.get("userChips", t.chips.get(sid, 0))
if d.get("caption"):
t.aktion[sid] = d["caption"]
elif cmd == "game.dealer_cards":
t.neuer_hand(d.get("gameHandId"))
t.board = _board(d.get("dealerCards"))
elif cmd == "game.hole_cards":
hole[d.get("gameHandId")] = d.get("holeCards")
elif cmd == "game.user_turn":
if not d.get("userTurnOptions"):
continue
karten = hole.get(d.get("gameHandId"))
if not karten:
continue
d["_hero"] = [_card(c) for c in karten]
zeile = json.dumps(t.anfrage(d), ensure_ascii=False)
kurz = (f"{d.get('gameHandId')} {_street_of(t.board):<7} "
f"toCall {d.get('callAmount')} Pot {d.get('totalPot')} "
f"Gegner {len(t.namen) - 1}")
ergebnis.append((zeile, kurz, raum, d.get("gameHandId"), d.get("turnTime")))
return ergebnis
def aus_dateien(pfade):
return spots("".join(open(p, errors="replace").read() for p in pfade))
if __name__ == "__main__":
import glob
pfade = sorted(glob.glob(os.path.join(WURZEL, "archiv", "*.log")))
for zeile, kurz, raum, hand in aus_dateien(pfade):
print(f"{raum[-8:]} {kurz}")
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env node
// Steuert die Client-Oberfläche über das Debug-Port - ohne Koordinaten.
//
// node cdp.mjs --text # sichtbare Texte auflisten
// node cdp.mjs --click "Join" # Element über seinen Text klicken
// node cdp.mjs --eval "<js>" # beliebigen Ausdruck auswerten
//
// Die Seite wird über ihren Zieldaten ermittelt; geklickt wird der kleinste
// passende Knoten, damit nicht ein umschliessender Container getroffen wird.
const PORT = process.env.CDP_PORT || 9333;
const args = process.argv.slice(2);
function flag(name) {
const i = args.indexOf(name);
return i < 0 ? null : (args[i + 1] ?? true);
}
async function seite() {
const liste = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
return liste.find((t) => t.type === "page" && (t.url || "").includes("lobby"))
|| liste.find((t) => t.type === "page");
}
const SICHTBAR = `n.offsetParent !== null && (n.innerText || "").trim().length > 0`;
const KLICK = (text) => `(() => {
const wollen = ${JSON.stringify(text)}.trim().toLowerCase();
const alle = [...document.querySelectorAll('button, a, [role="button"], span, div, li')]
.filter((n) => ${SICHTBAR});
const genau = alle.filter((n) => (n.innerText || "").trim().toLowerCase() === wollen)
.sort((a, b) => {
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
return ra.width * ra.height - rb.width * rb.height;
});
const teil = alle.filter((n) => (n.innerText || "").trim().toLowerCase().startsWith(wollen))
.sort((a, b) => {
const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect();
return ra.width * ra.height - rb.width * rb.height;
});
const ziel = genau[0] || teil[0];
if (!ziel) return "nichts gefunden fuer: " + wollen;
const r = ziel.getBoundingClientRect();
const opt = { bubbles: true, cancelable: true, composed: true, button: 0,
clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 };
for (const art of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
const ev = art.startsWith("pointer") ? new PointerEvent(art, opt) : new MouseEvent(art, opt);
ziel.dispatchEvent(ev);
}
return "geklickt: " + (ziel.innerText || "").trim().replace(/\\s+/g, " ").slice(0, 50)
+ " [" + Math.round(r.width) + "x" + Math.round(r.height) + "]";
})()`;
const TEXTE = `(() => {
const knoten = [...document.querySelectorAll('button, a, [role="button"], span, div, th, td')]
.filter((n) => ${SICHTBAR} && n.children.length === 0);
const gesehen = new Set(); const aus = [];
for (const n of knoten) {
const t = (n.innerText || "").trim().replace(/\\s+/g, " ");
if (!t || t.length > 40 || gesehen.has(t)) continue;
gesehen.add(t); aus.push(t);
}
return aus.join(" | ");
})()`;
// Wie KLICK, aber der n-te Treffer (0-basiert, in Reihenfolge der Seite).
const KLICK_NTH = (text, n) => `(() => {
const wollen = ${JSON.stringify(text)}.trim().toLowerCase();
const treffer = [...document.querySelectorAll('button, a, [role="button"], span, div')]
.filter((k) => k.offsetParent !== null &&
(k.innerText || "").trim().toLowerCase() === wollen);
if (!treffer.length) return "nichts gefunden: " + wollen;
const ziel = treffer[Math.min(${Number(n) || 0}, treffer.length - 1)];
const r = ziel.getBoundingClientRect();
const opt = { bubbles: true, cancelable: true, composed: true, button: 0,
clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 };
for (const art of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
const ev = art.startsWith("pointer") ? new PointerEvent(art, opt) : new MouseEvent(art, opt);
ziel.dispatchEvent(ev);
}
const zeile = (ziel.closest("tr, li, [class*=row], [class*=Row]") || ziel).innerText || "";
return "geklickt #" + ${Number(n) || 0} + " von " + treffer.length + ": "
+ zeile.replace(/\\s+/g, " ").slice(0, 60);
})()`;
// Klickt einen Knopf INNERHALB der Zeile, die einen Text enthält.
const KLICK_IN = (zeilenText, knopfText) => `(() => {
const zeile = ${JSON.stringify(zeilenText)}.trim().toLowerCase();
const knopf = ${JSON.stringify(knopfText)}.trim().toLowerCase();
const sichtbar = (n) => n.offsetParent !== null;
const flaeche = (n) => { const r = n.getBoundingClientRect(); return r.width * r.height; };
const treffer = [...document.querySelectorAll("*")]
.filter((n) => sichtbar(n) && (n.innerText || "").toLowerCase().includes(zeile))
.sort((a, b) => flaeche(a) - flaeche(b));
for (const z of treffer) {
const knoepfe = [...z.querySelectorAll('button, a, [role="button"], span, div')]
.filter((n) => sichtbar(n) && (n.innerText || "").trim().toLowerCase() === knopf)
.sort((a, b) => flaeche(a) - flaeche(b));
if (!knoepfe.length) continue;
const ziel = knoepfe[0];
const r = ziel.getBoundingClientRect();
const opt = { bubbles: true, cancelable: true, composed: true, button: 0,
clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 };
for (const art of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) {
const ev = art.startsWith("pointer") ? new PointerEvent(art, opt) : new MouseEvent(art, opt);
ziel.dispatchEvent(ev);
}
return "geklickt in Zeile '" + ${JSON.stringify(zeilenText)} + "': "
+ (ziel.innerText || "").trim().slice(0, 30);
}
return "kein Knopf '" + knopf + "' in der Zeile gefunden";
})()`;
async function main() {
const t = await seite();
if (!t) { console.log("keine Seite am Debug-Port"); process.exit(1); }
const ws = new WebSocket(t.webSocketDebuggerUrl);
await new Promise((ok, bad) => { ws.onopen = ok; ws.onerror = bad; });
let nr = 0; const wartend = new Map();
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
if (m.id && wartend.has(m.id)) { wartend.get(m.id)(m); wartend.delete(m.id); }
};
const senden = (method, params = {}) => new Promise((res) => {
const i = ++nr; wartend.set(i, res); ws.send(JSON.stringify({ id: i, method, params }));
});
await senden("Runtime.enable");
const werten = async (expr) => {
const r = await senden("Runtime.evaluate",
{ expression: expr, returnByValue: true, awaitPromise: true });
if (r.result?.exceptionDetails) return "Fehler: " + JSON.stringify(r.result.exceptionDetails).slice(0, 300);
return r.result?.result?.value;
};
const klick = flag("--click");
if (klick) { console.log(await werten(KLICK(klick))); ws.close(); return; }
if (args.includes("--click-in")) {
const i = args.indexOf("--click-in");
console.log(await werten(KLICK_IN(args[i + 1], args[i + 2] || "Join")));
ws.close();
return;
}
if (args.includes("--click-nth")) {
const i = args.indexOf("--click-nth");
console.log(await werten(KLICK_NTH(args[i + 1], args[i + 2])));
ws.close();
return;
}
const js = args.includes("--eval") ? args[args.indexOf("--eval") + 1] : null;
if (js) { console.log(await werten(js)); ws.close(); return; }
console.log("Titel:", await werten("document.title"));
console.log("Adresse:", await werten("location.href"));
console.log("Texte:", await werten(TEXTE));
ws.close();
}
main().catch((e) => { console.error("Fehler:", e.message); process.exit(1); });
@@ -0,0 +1,100 @@
# 00 — Overview: Autonomous CoinPoker Cash Agent
## Goal
A fully automatic agent that plays CoinPoker NLHE cash games on one Apple Silicon Mac with one
account, and whose behaviour is **statistically indistinguishable from the account's own existing
human play**. Two properties define success:
1. **Correct enough to act unattended** — it perceives the table, decides legally, and clicks.
2. **Unremarkable enough to survive** — its timing and style match the human baseline, so
behavioural bot detection has nothing to latch onto.
## Why this shape: the Anti-Guess Doctrine
The project is designed so that almost nothing is discovered by trial-and-error at a live table.
Five laws drive every decision downstream.
1. **Truth before code.**
CoinPoker's own hand history is an *exact answer key*: hole cards, board, every action, every
amount, stack sizes, seats, timestamps. Recording a play session and exporting its hand history
produces a **Golden Corpus** — frozen pairs of (screenshot → true state). Screen reading then
becomes a deterministic, offline assertion over thousands of hands instead of live guessing.
2. **Enumerate, do not fit.**
The visible state space is finite: 52 cards, 10 digits, a handful of action buttons, a bounded
number of seats and streets. The client's own rendering assets become the recognition templates.
Coverage is therefore a *checklist*, not a hope.
3. **The client version is the calibration anchor.**
Pin the client version. The corpus doubles as a regression suite: a client update reports exactly
what broke, in milliseconds — instead of costing money at a live table.
4. **"I don't know" is a legal outcome.**
The perception layer may return *Unknown* with a confidence and a reason. When it is unknown, the
agent does not act blindly — it abstains. Abstention is a first-class domain state, not a bug.
5. **Invisibility is measured, not hoped.**
CoinPoker's own words: they flag "non-human actions", "unnatural decision-timing", and even
"perfect GTO play"; they hunt via player reports. So the reference is not "a human in general" but
**this account's own history**. The baseline profile — VPIP, PFR, 3-bet, aggression frequency,
bet-size mix, decision-time distribution — is harvested from the owner's own manual sessions.
Deviation becomes a number with a confidence interval.
## Enforcement context (the WHY for the caution)
Documented enforcement is real, hard and retroactive: a ban wave of 98 bot accounts with ~$156k
returned to players; bans against **seat-selection scripts alone**; documented confiscations of
around 10k USDT; sanctions justified under the clauses covering bots/scripts/AI and RTA/solvers.
Two consequences shape the plan:
- **Compliance is binary.** Their third-party-tool rules forbid everything except their built-in HUD
and PokerIntel — so a HUD is already a violation, and a bot costs no extra compliance. Half-measures
buy nothing.
- **The balance is the exposure.** Bans arrive retroactively, so the wallet, not the engine, is the
thing to manage: keep it small, withdraw in crypto regularly, prefer cash games over tournaments.
## Scope
**In:** one account, one macOS machine, no virtual machine. NLHE cash games on regular tables first;
K-Poker only after the perception and timing layers are proven.
**Out initially:** tournaments, PLO / Short Deck / Bomb Pot / All-In or Fold, multi-account,
in-process client hook, Windows, remote/cloud execution.
## Ubiquitous Language
Naming is domain-specific throughout; no generic buckets. Core terms:
- **Table, Seat, SeatIndex, HeroSeat** — physical table and a seat identity, Hero's seat included.
- **HoleCards, Board, Street** — Hero's private cards, community cards, and the street
(preflop / flop / turn / river / showdown).
- **PotSize, StackSize, Chips, AmountToCall** — money quantities as value objects.
- **RaiseBounds, LegalActions, Action, ActionKind** — what is permitted, and the chosen act
(fold / check / call / bet / raise / all-in).
- **DecisionPoint, DecisionDeadline** — the moment the agent must act, and the measured time it has.
- **TemplateId, CardTemplate, RegionSpec, ExtractionReport, Confidence, UnknownReason** — perception.
- **HandId, HandRecord, HandHistory** — the answer key and its units.
- **GoldenCase** — one frozen (screenshot, expected state, source hand) artifact.
- **ExtractionFidelity** — share of GoldenCases reproduced exactly.
- **Equity, WinProbability, ExpectedValue, Thresholds** — the decision mathematics.
- **DecisionPolicy, PreflopChartPolicy, PostflopEVPolicy, BetSizeMix** — how an action is chosen.
- **TimingSample, HumanTimingProfile, DifficultyScore, DelaySampler** — the human imitation layer.
- **DeviationRate** — calibrated, deliberate departure from the optimal line.
- **ShadowRun, ShadowLog, Abstention** — the risk-free rehearsal mode and its record.
## Document index
- `00_OVERVIEW.md` — this file: goal, doctrine, scope, language.
- `01_FAILING_TESTS.md` — the TDD targets, the corpus fixture strategy, the declared edge inventory,
the exact test commands, and what must never be asserted.
- `02_ARCHITECTURE_AND_EXECUTION.md` — module map, the step-by-step Red→Green execution plan, the
verification gates, and the residual-risk register.
## Open questions resolved by measurement, never by assumption
- The real decision clock per format *and whether a time bank exists*. Only K-Poker is documented
(10 s, no time bank mentioned); every other format documents no clock at all. Both properties are
measured from recordings during the corpus phase.
- Maximum simultaneous tables.
- Hand-history export cadence (documented as manual via PokerIntel, not a live file).
@@ -0,0 +1,96 @@
# 01 — Test Targets (Red first, zero production code)
Everything here is written **before** implementation. Tests assert on domain outcomes — returned
value objects, derived state, domain errors, fidelity counts. Nothing asserts on styling, layout,
class names or logger calls.
## Fixture doctrine: the Golden Corpus
The corpus is the anti-guess instrument. It is captured, never invented.
- **Capture shape:** a recording session (screen images + the hand history exported for the same
session) plus its pin of the client version. Alignment between images and hands uses the hand
timestamps in the history.
- **Two fixture kinds:** (a) *full-hand replays* — an ordered image sequence with the expected state
at each step and the expected final hand record; (b) *atomic edge fixtures* — a single region
containing one card, one number, one button state.
- **Offline and fast:** no CoinPoker, no network, no sleeps. A corpus assertion must run in
milliseconds so that it can be run after every edit.
## Tier 1 — Pure domain, zero I/O
Targets, each a spec in its own micro-module:
- Card and suit recognition from a template identity, in both directions.
- Numeric reading: chips, pot, bets, stacks, including separators, all-in markers and side pots.
- Street derivation; dealer/button position; blind, straddle and ante handling.
- Legality derivation: fold/check/call/bet/raise, minimum raise, maximum raise, amount to call.
- Turn detection: whose turn it is, Hero included; overlapping turns across tables.
- Equity and win probability; pot odds; expected value of each legal action.
- Preflop chart lookup by position, action sequence and stack depth.
- Postflop policy: threshold behaviour between fold/call/raise for a given equity and price.
- Timing policy: a difficulty score mapped to a human-plausible delay sampled from the profile.
- Deliberate deviation: the deviation decision is reproducible under a fixed seed.
- Abstention: an *Unknown* region yields abstention, never a guess.
### EDGE INVENTORY (declared input-space map)
The map is declared up front so coverage is a checklist, not a hope:
- **Cards:** 13 ranks × 4 suits = 52; board lengths 0–5; any Hero seat; seat counts 2–7.
- **Streets:** preflop, flop, turn, river, showdown.
- **Actions:** fold, check, call, bet, raise, re-raise, all-in.
- **Amounts:** 0–7 digits, with and without separators, all-in, side pot, split pot.
- **Structure:** heads-up blinds, dead blinds, ante-only, forced ante every hand, bomb pot
(no preflop street).
- **Temporal:** turn arrives while another table's turn is open; turn arrives during a disconnect
countdown; run-it-twice offered.
- **Deadline:** deadline unknown (format without documented clock); deadline shrinking mid-decision.
Property-based cases are used where an invariant exists (pot conservation, legality, monotonicity of
equity in the number of opponents) instead of hand-imagining cases one by one.
### Mutation targets
Each objective must kill mutants on its boundary conditions, not only on the happy path:
minimum-raise and amount-to-call comparisons, the equity threshold separating call from raise, the
preflop chart's raise/fold boundary, the difficulty-to-delay threshold, and the deviation draw.
## Tier 2 — Adapters, offline against the corpus
- **Extraction spec:** for every GoldenCase the extracted state equals the expected state exactly, or
returns Unknown with a named reason. Fidelity is asserted as a number and must reach 100% over the
corpus; the first miss becomes a named corpus case.
- **Click planning:** given a state and a chosen action, the produced click target lands inside the
intended button's recorded region for that case.
- **Corpus regression:** after a client-version bump, the same corpus runs and reports precisely
which cases drifted.
- **Shadow log round-trip:** a shadow record survives write and read unchanged.
## Tier 3 — E2E, final verification only
- **Live shadow run:** replay N real hands with the agent watching. Afterwards assert (a) extraction
fidelity against the freshly exported history is 100%, (b) zero illegal actions, (c) the observed
timing distribution is statistically compatible with the human baseline within the declared
tolerance.
- **Soak:** several hours across several tables; stable memory; no drift in fidelity.
- **Teardown:** no orphaned state, no leftover scratch artifacts, no polluted logs.
## Exact commands (laser-targeted; never an unbounded suite)
- Unit target: the crate's single spec file for the module under change.
- Adapter target: the extraction or click-plan spec, with the corpus index as input.
- Mutation proof: list the file's mutable literals first, then mutate the chosen literal and expect
the target spec to go red, then restore.
- Regression sweep: the full corpus spec, run only at objective boundaries.
## RED / GREEN expectations
Per objective: the spec is authored in one batch and executed once; red must be caused by *missing
implementation*, not by a syntax error. Green must be followed by the mutation proof and an edge
pass against the declared inventory. A green run that executed zero cases counts as failed.
## Never asserted
Font sizes, pixel colours, CSS or widget class names, logger output, and framework wiring. The only
pixel-adjacent assertions live in Tier 2, where a click must land in a region.
@@ -0,0 +1,121 @@
# 02 — Architecture & Execution
## Architectural shape
Functional core, imperative shell. The poker domain is pure and has zero dependency on screens,
windows, files or time. Every effect lives in an adapter behind a port.
- **Pure core:** perception parsing, legality, equity and EV, policy, human imitation, state machine.
- **Imperative shell:** screen capture, template matching, clicking, clock, corpus and shadow storage.
- **Ports:** ScreenSource, StateExtractor, ActionSink, ClockSource, CorpusStore, ShadowStore.
Because perception is a *port*, it is swappable: today a screen-based extractor; later an in-process
client hook can replace it without touching the domain.
## Module map (one concept per file, 50–200 lines, hard ceiling 500)
**Poker value objects:** Rank, Suit, Card, HoleCards, Board, Street, SeatIndex, Seat, Chips,
StackSize, PotSize, AmountToCall, RaiseBounds, LegalActions, Action, ActionKind.
**Table state:** SeatMap, HeroSeat, DecisionPoint, DecisionDeadline, TableState, TableId.
**History:** HandId, HandRecord, ActionRecord, HandHistory.
**Perception:** TemplateId, CardTemplate, DigitTemplate, RegionSpec, RegionReading, ExtractionReport,
Confidence, UnknownReason.
**Decision:** Equity, WinProbability, ExpectedValue, Thresholds, ChartKey, PreflopChart,
DecisionPolicy, PreflopChartPolicy, PostflopEVPolicy, BetSizeMix.
**Human imitation:** TimingSample, HumanTimingProfile, DifficultyScore, DelaySampler,
CoordinateJitter, DeviationRate.
**Orchestration:** HandStateMachine, TurnDetector, Abstention, ShadowRunner, AutonomyRunner.
**Adapters:** MacScreenSource, TemplateMatcher, QuartzClickSink, MonotonicClock, CorpusFiles,
ShadowLogFile, ClientVersionPin.
## Execution plan (each step = one Red→Green→Refactor cycle ending in a mutation proof)
### Phase A — Corpus and measurement (no agent yet, zero risk)
- A1 A read-only recording watcher: while the owner plays normally, it timestamps state changes and
the owner's own clicks. Output: sessions plus their exported hand history, aligned by timestamp.
- A2 Measure the real decision clock per format from the recordings, and record whether a time bank
exists. The deadline becomes a measured domain quantity instead of an assumption.
- A3 Pin the client version and index the corpus.
**Gate A:** the corpus loads, the index is complete, deadlines are measured quantities.
### Phase B — Perception against truth
- B1 Card, rank and suit recognition built from the client's own assets.
- B2 Numeric reading: pot, bets, stacks, all-in, side pot.
- B3 Seat and turn detection, button position, street detection, Hero seat.
- B4 Assembly into a full table state, with Unknown where a region is unresolved.
**Gate B:** extraction fidelity reaches 100% over the corpus; every miss has become a named case.
### Phase C — Decision core (pure)
- C1 Preflop chart policy: exact, deterministic, offline-measurable.
- C2 Equity, EV and the postflop policy.
- C3 Legality guards: an illegal action is impossible; otherwise abstain.
**Gate C:** preflop decisions are reproducible from the corpus; illegal actions number zero.
**Honest limit:** replaying postflop is counterfactual, because the owner's own actions shaped the
line. Postflop quality is therefore approximate offline and authoritative only in shadow mode.
### Phase D — Human imitation
- D1 Harvest the account's own style profile and timing profile from its real sessions.
- D2 Delay sampled from the profile, conditioned on decision difficulty; jittered click targets;
deliberate sub-optimal deviations at a calibrated rate.
- D3 Statistical gates rather than intuition: a two-sample test on the delay distribution, a
confidence interval on action frequencies, and plausibility checks (no zero-millisecond actions,
no constant delay).
**Gate D:** the agent's timing and style are statistically compatible with the owner's baseline
within the declared tolerance.
### Phase E — Actuator
- E1 Background clicking into the client window, without stealing focus, so the owner keeps working.
- E2 Full shadow loop: the agent decides, the owner still clicks.
**Gate E:** N hands with zero illegal actions, no abstention storms, timing inside tolerance.
### Phase F — Autonomy
- F1 The owner stops clicking. Soak run with alerts on abstention or falling confidence.
- F2 Sequencing: regular NLHE first, because its clock is undocumented and must be measured while
likely generous; K-Poker last, because its 10-second clock is the tightest documented case.
**Gate F:** sustained run at stable fidelity, with withdrawal discipline in place.
## Verification gates — the no-guessing ledger
| Gate | Property | Nature |
| :--- | :--- | :--- |
| Extraction fidelity vs exported history | perception is correct | deterministic |
| Corpus regression after client update | nothing silently drifted | deterministic |
| Illegal-action count | decisions are legal | deterministic |
| Offline preflop EV | preflop policy is sound | near-causal |
| Delay and style vs human baseline | invisible to behaviour analysis | statistical |
| Balance small, withdrawals regular | blast radius of a retroactive ban | procedural |
## Residual risk — what stays genuinely uncertain
Client layout changes; a new game format; run-it-twice and disconnect handling; capture load across
many tables; the endogeneity of postflop replay; and the irreducible fact that a bot is *by design* a
rule violation, so enforcement stays discretionary.
Mitigations: abstention instead of guessing, corpus regression on every client bump, starting on
formats with the most slack, staying on low-stakes tables where player reports are rare, and keeping
little money on the site.
## Non-negotiables
One account, one device, no virtual machine. Cash games before tournaments. Small balance, regular
crypto withdrawals. No suppression of failing assertions; tests are immutable once written.
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Spezifikation der Denkzeit - geschrieben VOR dem Code.
Geprüft wird ausschliesslich Verhalten, das ein Mensch auch zeigen würde:
Untergrenze, rechtsschiefe Verteilung, Abhängigkeit von der Knappheit,
gelegentliche lange Pause, Wandern über die Sitzung, Uhr-Grenze, Seed.
python3 -m unittest denkzeit_spec -v
"""
import os as _os, sys as _sys
_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
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import random
import statistics
import unittest
import denkzeit
ANFRAGE = {"pot": 1.0, "toCall": 0.5, "street": "RIVER", "turnTime": 16}
SICHER = {"action": "RAISE", "confidence": 0.95, "equity": 0.80}
KNAPP = {"action": "CALL", "confidence": 0.55, "equity": 0.26}
class Profil(unittest.TestCase):
def test_standardprofil_ist_plausibel(self):
p = denkzeit.STANDARD
self.assertGreater(p["min_ms"], 300, "Menschen denken nicht in Millisekunden")
self.assertGreater(p["median_ms"], p["min_ms"])
self.assertGreater(p["max_ms"], p["median_ms"])
self.assertTrue(0.0 < p["tank_rate"] < 0.5)
def test_profil_hat_genau_die_vereinbarten_felder(self):
self.assertEqual(set(denkzeit.STANDARD),
{"min_ms", "median_ms", "spread_ms", "tank_rate", "max_ms"})
class Knappheit(unittest.TestCase):
def test_liegt_zwischen_null_und_eins(self):
for antwort in (SICHER, KNAPP, {"action": "CHECK", "confidence": 0.5}):
wert = denkzeit.knappheit(ANFRAGE, antwort)
self.assertGreaterEqual(wert, 0.0)
self.assertLessEqual(wert, 1.0)
def test_geringere_konfidenz_ist_knapper(self):
sicher = denkzeit.knappheit(ANFRAGE, {"action": "CALL", "confidence": 0.9})
unsicher = denkzeit.knappheit(ANFRAGE, {"action": "CALL", "confidence": 0.55})
self.assertGreater(unsicher, sicher)
def test_equity_genau_am_bruchpunkt_ist_am_knappsten(self):
genau = denkzeit.knappheit(ANFRAGE, {"action": "CALL", "confidence": 0.9,
"equity": 0.5 / 1.5})
weit = denkzeit.knappheit(ANFRAGE, {"action": "CALL", "confidence": 0.9,
"equity": 0.95})
self.assertGreater(genau, weit)
def test_ohne_equity_faellt_es_auf_die_konfidenz_zurueck(self):
ohne = denkzeit.knappheit(ANFRAGE, {"action": "CALL", "confidence": 0.55})
self.assertGreater(ohne, 0.2)
class Wartezeit(unittest.TestCase):
def reihe(self, knappheit, seed=7, n=400, profil=None):
zufall = random.Random(seed)
p = profil or denkzeit.STANDARD
return [denkzeit.wartezeit(knappheit, p, zufall) for _ in range(n)]
def test_untergrenze_und_obergrenze_halten(self):
p = denkzeit.STANDARD
for wert in self.reihe(0.5) + self.reihe(1.0):
self.assertGreaterEqual(wert, p["min_ms"])
self.assertLessEqual(wert, p["max_ms"])
def test_nie_konstant(self):
self.assertGreater(len(set(self.reihe(0.5))), 50)
def test_rechtsschief(self):
reihe = self.reihe(0.5)
self.assertGreater(statistics.mean(reihe), statistics.median(reihe))
self.assertGreater(statistics.quantiles(reihe, n=10)[8],
2 * statistics.median(reihe))
def test_knappere_lagen_dauern_laenger(self):
sicher = statistics.median(self.reihe(0.0))
knapp = statistics.median(self.reihe(1.0))
self.assertGreater(knapp, sicher * 1.2)
def test_gelegentliche_lange_pause(self):
p = dict(denkzeit.STANDARD, tank_rate=0.3)
reihe = self.reihe(0.5, profil=p)
lang = [w for w in reihe if w > statistics.median(reihe) * 1.7]
self.assertGreater(len(lang), len(reihe) * 0.1)
self.assertLess(len(lang), len(reihe) * 0.6)
def test_gleicher_seed_gleiche_reihe(self):
self.assertEqual(self.reihe(0.4, seed=11, n=50), self.reihe(0.4, seed=11, n=50))
def test_verschiedene_seeds_andere_reihe(self):
self.assertNotEqual(self.reihe(0.4, seed=11, n=50), self.reihe(0.4, seed=12, n=50))
class Uhr(unittest.TestCase):
def test_haelt_sich_an_die_bedenkzeit(self):
self.assertLessEqual(denkzeit.mit_uhr(8000.0, 16.0), 9600.0)
def test_lange_zeit_bleibt_unangetastet(self):
self.assertEqual(denkzeit.mit_uhr(1000.0, 30.0), 1000.0)
def test_ohne_uhr_keine_grenze(self):
self.assertEqual(denkzeit.mit_uhr(3000.0, None), 3000.0)
class Wandern(unittest.TestCase):
def test_verteilung_wandert_langsam(self):
# Ein gemeinsamer Generator: ein frischer je Aufruf kann kein Wandern zeigen.
zufall = random.Random(3)
reihe = [denkzeit.wartezeit(0.4, denkzeit.STANDARD, zufall) for _ in range(3000)]
drittel = len(reihe) // 3
anfang = statistics.median(reihe[:drittel])
ende = statistics.median(reihe[-drittel:])
self.assertGreater(abs(ende - anfang), 0.5, "ohne Wandern wirkt es statisch")
self.assertLess(abs(ende - anfang), anfang * 0.6, "Wandern darf nicht springen")
class Vermessung(unittest.TestCase):
def test_profil_aus_trockendaten(self):
"""Ohne Korpus muss trotzdem ein vollständiges Profil herauskommen."""
p = denkzeit.profil_aus_log([])
self.assertEqual(set(p), set(denkzeit.STANDARD))
self.assertGreater(p["median_ms"], p["min_ms"])
if __name__ == "__main__":
unittest.main()