Files

149 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Testet Tastenkürzel des Tischfensters - sauber, eine Taste pro Zug.
Erfolg heisst: der Zug ist danach vorbei (der Client meldet den naechsten Spieler
oder game.advance_player_action). Das ist der verlaesslichste Beweis, dass der
Tastendruck angekommen und gewirkt hat.
python3 keytest.py [--minutes 30]
"""
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", "mock"):
_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 re
import subprocess
import sys
import time
BASE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
OUT = os.path.join(BASE, "scratch", "keytest-log.txt")
EVENT = re.compile(
r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"'
)
USER = re.compile(r"username=([A-Za-z0-9_]+)")
KEYS = ["f", "c", "r", "space", "a", "b"]
TURN_OVER = ("advance_player_action", "ACTION_TYPE")
class LogTail:
def __init__(self, path):
self.path, self.handle, self.inode = path, None, None
self._open(True)
def _open(self, from_end):
if self.handle:
self.handle.close()
self.handle = open(self.path, errors="replace")
if from_end:
self.handle.seek(0, 2)
self.inode = os.fstat(self.handle.fileno()).st_ino
def line(self):
found = self.handle.readline()
if found:
return found
try:
if os.stat(self.path).st_ino != self.inode:
self._open(False)
except FileNotFoundError:
pass
return ""
def press(key):
cmd = [sys.executable, os.path.join(BASE, "press.py"), key]
return subprocess.run(cmd, capture_output=True, text=True).stdout.strip()
def main():
minutes = 30.0
if "--minutes" in sys.argv:
minutes = float(sys.argv[sys.argv.index("--minutes") + 1])
out = open(OUT, "w")
def note(text):
out.write(text + "\n")
out.flush()
tail = LogTail(LOG)
note(f"# Sauberer Tastentest {time.strftime('%H:%M:%S')} | Tasten {KEYS} | "
f"eine Taste pro Zug | Erfolg = Zug danach vorbei")
me = None
index = 0
armed = True # darf gedrueckt werden?
results = []
end = time.time() + minutes * 60
while time.time() < end and index < len(KEYS):
line = tail.line()
if not line:
time.sleep(0.1)
continue
who = USER.search(line)
if who:
me = who.group(1)
if any(t in line for t in TURN_OVER):
armed = True
hit = EVENT.search(line)
if not hit or hit.group(2) != "game.user_turn":
continue
try:
data = json.loads(json.loads('"' + hit.group(1) + '"'))
except Exception:
continue
options = {s: v for s, v in (data.get("userTurnOptions") or {}).items() if v}
if options:
me = data.get("whoseTurn") or me
elif me is None or data.get("whoseTurn") != me:
continue
if not armed:
continue
key = KEYS[index]
note(f"\n=== Zug | {time.strftime('%H:%M:%S')} | Taste '{key}' | Hand "
f"{data.get('gameHandId')} | Call {data.get('callAmount')} "
f"Pot {data.get('totalPot')} | ich={me}")
note(" " + press(key))
armed = False
started = time.time()
proof = []
while time.time() - started < 2.5:
more = tail.line()
if not more:
time.sleep(0.04)
continue
if any(t in more for t in TURN_OVER):
proof.append(f"+{int((time.time()-started)*1000)}ms {more.strip()[:170]}")
if proof:
results.append((key, proof[0]))
note(f" WIRKT - der Zug war danach vorbei:")
for p in proof[:3]:
note(f" {p}")
index += 1
else:
note(" ohne Wirkung")
note("\n# Ergebnis")
if results:
for key, p in results:
note(f" Taste '{key}' wirkt -> {p[:130]}")
else:
note(" keine Taste hat gewirkt")
note(f"# beendet nach {index} bestaetigten Tasten")
out.close()
if __name__ == "__main__":
main()