#!/usr/bin/env python3 """Query / verify a raw Tank Royale battle recording (.battle.gz, gzipped ND-JSON). The recording is the UNFILTERED raw observer stream: one verbatim server message per line. Each line is a JSON object with a top-level "type". TickEventForObserver lines carry turnNumber, roundNumber, botStates[], bulletStates[], events[]. Usage: # integrity report (turn continuity, bot presence, event histogram) query.py --verify FILE.battle.gz # compact tick table for a turn range (any range, any recording) query.py FILE.battle.gz --range 300 340 query.py FILE.battle.gz --range 300 340 --round 2 query.py FILE.battle.gz --auto 40 # 40 ticks around the first bullet being fired """ import argparse, collections, gzip, json, sys def read(path): op = gzip.open if path.endswith(".gz") else open with op(path, "rt") as fh: for line in fh: line = line.strip() if line: try: yield json.loads(line) except json.JSONDecodeError: yield {"type": ""} def load(path, rnd=None): ticks, top = [], collections.Counter() for m in read(path): top[m.get("type")] += 1 if m.get("type") == "TickEventForObserver" and (rnd is None or m.get("roundNumber") == rnd): ticks.append(m) return ticks, top def verify(path, ticks, top): print("== top-level types on the wire ==") for k, v in top.most_common(): print(f" {v:7d} {k}") turns = [t["turnNumber"] for t in ticks] print("\n== turnNumber continuity ==") if not turns: print(" NO TICKS"); return print(f" count={len(turns)} min={min(turns)} max={max(turns)} distinct={len(set(turns))}") per_round = collections.defaultdict(list) for t in ticks: per_round[t["roundNumber"]].append(t["turnNumber"]) gaps = dups = 0 for r, ts in sorted(per_round.items()): s = sorted(ts) g = [(a, b) for a, b in zip(s, s[1:]) if b - a != 1] d = [k for k, v in collections.Counter(ts).items() if v > 1] gaps += sum(b - a - 1 for a, b in g) dups += len(d) print(f" round {r}: {len(s)} turns [{s[0]}..{s[-1]}] gaps={g if g else 'NONE'} dups={d if d else 'NONE'}") print(f" VERDICT: {'CONTIGUOUS, no drops' if gaps == 0 and dups == 0 else f'BROKEN ({gaps} missing turns, {dups} duplicated)'}") print("\n== bots ==") ids = collections.Counter() for t in ticks: ids[tuple(sorted(b["id"] for b in t["botStates"]))] += 1 for b in t["botStates"]: pass names = {b["id"]: b["name"] for t in ticks for b in t["botStates"]} for k, v in ids.items(): print(f" bot-id-set {k} ({', '.join(names.get(i, '?') for i in k)}): {v}/{len(ticks)} ticks") owners = collections.Counter() for t in ticks: owners[tuple(sorted(bs.get("ownerId") for bs in t["bulletStates"]))] += 1 print(f" bulletStates ownerId sets: {dict(owners)} (empty = no bullets in flight)") print("\n== events[] histogram (inner) ==") h = collections.Counter() for t in ticks: for e in t["events"]: h[e.get("type")] += 1 for k, v in h.most_common(): print(f" {v:7d} {k}") for want in ["BulletFiredEvent", "BulletHitBotEvent", "BulletHitWallEvent", "BulletHitBulletEvent", "ScannedBotEvent", "BotDeathEvent"]: print(f" {'OK ' if h.get(want) else 'MISS'} {want}: {h.get(want, 0)}") def table(ticks): names = {b["id"]: b["name"][:11] for t in ticks for b in t["botStates"]} print(f"{'turn':>5} {'bots':<26} {'bullets':>7} events") for t in ticks: bs = " | ".join(f"#{b['id']} {names[b['id']]:<11} ({b['x']:6.1f},{b['y']:6.1f}) d={b['direction']:6.1f} g={b['gunDirection']:6.1f}" for b in sorted(t["botStates"], key=lambda x: x["id"])) ev = " ".join(f"{e.get('type')}({','.join(f'{k}={v}' for k, v in sorted(e.items()) if k not in ('type',))})" for e in t["events"]) or "-" print(f"{t['turnNumber']:5d} {bs:<62} {len(t['bulletStates']):7d} {ev}") def main(): ap = argparse.ArgumentParser() ap.add_argument("file") ap.add_argument("--verify", action="store_true") ap.add_argument("--range", nargs=2, type=int, metavar=("LO", "HI")) ap.add_argument("--round", type=int, dest="rnd") ap.add_argument("--auto", type=int, metavar="N", help="N ticks around the first bullet firing") a = ap.parse_args() ticks, top = load(a.file, a.rnd) if a.verify: verify(a.file, ticks, top) if a.range: lo, hi = a.range sel = [t for t in ticks if lo <= t["turnNumber"] <= hi] elif a.auto: hit = next((t["turnNumber"] for t in ticks if any(e.get("type") == "BulletFiredEvent" for e in t["events"])), None) if hit is None: sys.exit("no BulletFiredEvent in this recording") sel = [t for t in ticks if hit <= t["turnNumber"] <= hit + a.auto - 1] else: sel = ticks[:40] if not a.verify else [] if sel: print(f"\n== ticks {sel[0]['turnNumber']}..{sel[-1]['turnNumber']} " f"(round {sorted({t['roundNumber'] for t in sel})}) ==") table(sel) if __name__ == "__main__": main()