162 lines
5.3 KiB
Python
162 lines
5.3 KiB
Python
#!/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)
|