#!/usr/bin/env python3 """Bridge a Gomocup-protocol engine (Rapfi, xl, ...) into Renju Arena. The bridge connects to the arena's TCP line protocol and speaks Gomocup to a local engine. No third-party Python packages are required. Usage: python bridge_gomocup.py --engine "C:/engines/rapfi.exe" --token rnj_xxx python bridge_gomocup.py --engine ./xl.exe --host 192.168.1.10 --port 8788 --token rnj_xxx The engine is started with START 15 and Renju rule 4. A complete position is rebuilt with RESTART / BOARD / DONE before every move, so opening prefixes and color swaps cannot desynchronise it. """ from __future__ import annotations import argparse import queue import re import socket import subprocess import sys import threading import time COORD = re.compile(r"^\s*(-?\d+)\s*,\s*(-?\d+)\s*$") def parse_moves(field: str): if field == "-" or not field: return [] out = [] for item in field.split(";"): parts = item.split(",") if len(parts) == 3: out.append((int(parts[0]), int(parts[1]), int(parts[2]))) return out class ExternalEngine: def __init__(self, path): self.proc = subprocess.Popen( [path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, encoding="utf-8", errors="replace", windowsHide=True, ) self.q = queue.Queue() threading.Thread(target=self._reader, daemon=True).start() def _reader(self): try: for line in self.proc.stdout: self.q.put(line.strip()) except Exception: pass self.q.put(None) def send(self, line): if self.proc.poll() is not None: raise RuntimeError("Gomocup engine exited") self.proc.stdin.write(line + "\n") self.proc.stdin.flush() def read_line(self, timeout): try: return self.q.get(timeout=timeout) except queue.Empty: return None def expect_ok(self, timeout=5.0): deadline = time.monotonic() + timeout while time.monotonic() < deadline: line = self.read_line(max(0.01, deadline - time.monotonic())) if line is None: return False if line == "OK": return True if line.startswith(("ERROR", "UNKNOWN")): print("engine:", line, file=sys.stderr, flush=True) return False return False def expect_move(self, timeout): deadline = time.monotonic() + timeout while time.monotonic() < deadline: line = self.read_line(max(0.01, deadline - time.monotonic())) if line is None: return None m = COORD.match(line) if m: return int(m.group(1)), int(m.group(2)) if line.startswith(("ERROR", "UNKNOWN")): print("engine:", line, file=sys.stderr, flush=True) return None def close(self): try: if self.proc.poll() is None: self.proc.stdin.write("END\n") self.proc.stdin.flush() except Exception: pass try: self.proc.wait(timeout=1.0) except Exception: self.proc.kill() class ArenaBridge: def __init__(self, engine_path, host, port, token, verbose=True): self.sock = socket.create_connection((host, port), timeout=15) self.file = self.sock.makefile("r", encoding="utf-8", newline="\n") self.token = token self.verbose = verbose self.engine = ExternalEngine(engine_path) self.game_id = None self.color = "B" self.time_ms = 3000 self._engine_started = False def log(self, *args): if self.verbose: print(*args, flush=True) def send(self, line): self.log("→", line) self.sock.sendall((line + "\n").encode("utf-8")) def init_engine(self): if self._engine_started: return self.engine.send("START 15") if not self.engine.expect_ok(): raise RuntimeError("engine rejected START 15") self.engine.send("INFO rule 4") self.engine.send("INFO game_type 1") self.engine.send("INFO max_memory 134217728") self.engine.send("INFO timeout_match 100000000") self.engine.send("INFO time_left 100000000") self._engine_started = True def engine_move(self, moves): self.init_engine() self.engine.send(f"INFO timeout_turn {max(100, self.time_ms)}") self.engine.send(f"INFO time_left {max(1000, self.time_ms * 20)}") if self.color == "B" and not moves: self.engine.send("BEGIN") else: self.engine.send("RESTART") if not self.engine.expect_ok(): raise RuntimeError("engine rejected RESTART") self.engine.send("BOARD") for r, c, color in moves: mine = (color == 1 and self.color == "B") or (color == 2 and self.color == "W") self.engine.send(f"{c},{r},{1 if mine else 2}") self.engine.send("DONE") point = self.engine.expect_move(max(5.0, self.time_ms / 1000 + 4.0)) if point is None: raise RuntimeError("Gomocup engine did not return a coordinate") x, y = point return y, x # arena (row, col); Gomocup (x=col, y=row) def run(self): for raw in self.file: line = raw.strip() if not line: continue self.log("←", line) cmd, *parts = line.split(" ") if cmd == "HELLO_REQUIRED": self.send(f"HELLO {self.token} 1") elif cmd == "HELLO_OK": self.log("接入成功:", line) elif cmd == "MATCH": self.game_id = parts[0] self.color = parts[1] self.time_ms = int(parts[2]) if len(parts) > 2 else 3000 elif cmd == "TURN": game_id, color, ply, time_ms, *rest = parts self.game_id = game_id self.color = color self.time_ms = int(time_ms) moves = parse_moves(" ".join(rest)) try: r, c = self.engine_move(moves) except Exception as exc: print("bridge error:", exc, file=sys.stderr, flush=True) return self.send(f"MOVE {game_id} {r} {c}") elif cmd == "RESULT": self.log("对局结果:", line) elif cmd == "PING": self.send("PONG") elif cmd == "ERROR": print("arena:", line, file=sys.stderr, flush=True) def close(self): try: self.file.close() self.sock.close() except OSError: pass self.engine.close() def main(): ap = argparse.ArgumentParser(description="Gomocup -> Renju Arena bridge") ap.add_argument("--engine", required=True, help="Gomocup engine executable") ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=8788) ap.add_argument("--token", required=True) ap.add_argument("--quiet", action="store_true") args = ap.parse_args() bridge = ArenaBridge(args.engine, args.host, args.port, args.token, verbose=not args.quiet) try: bridge.run() except KeyboardInterrupt: pass except Exception as exc: print("bridge failed:", exc, file=sys.stderr) raise SystemExit(1) finally: bridge.close() if __name__ == "__main__": main()