"""A Gomocup match between two brains, as Piskvork runs one: the brains speak the Gomocup protocol on stdin and stdout (START, INFO, BEGIN, TURN, BOARD ... DONE, END), the board is 15x15 and the rule is standard: exactly five in a row wins, an overline does not. A match starts from a fixed opening of a few stones and is played twice with colours swapped, as Gomocup does. A brain that runs out of time, answers nonsense or plays on a stone loses. Renju's forbidden moves are not judged (ponytail: standard rule only; renju needs its own detector, the free ones are GPL). """ import os, queue, subprocess, threading, time D = [(1, 0), (0, 1), (1, 1), (1, -1)] class Brain: def __init__(self, argv, cwd): env = {k: v for k, v in os.environ.items() if not k.startswith(('SS_', 'SLURM_'))} self.p = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, env=env) self.q = queue.Queue() threading.Thread(target=lambda: [self.q.put(l) for l in self.p.stdout], daemon=True).start() def send(self, *lines): self.p.stdin.write(''.join(l + '\n' for l in lines)) self.p.stdin.flush() def reply(self, timeout): end = time.monotonic() + timeout while True: remaining = end - time.monotonic() if remaining <= 0: raise queue.Empty line = self.q.get(timeout=remaining).strip() cmd, _, arg = line.partition(' ') if cmd.upper() == 'SUGGEST': self.send(f'PLAY {arg}') elif line and cmd.upper() not in ('MESSAGE', 'DEBUG'): return line def run_of(board, x, y, c): best, line = 0, None for dx, dy in D: cells = [(x, y)] for s in (1, -1): i = 1 while board.get((x + s * i * dx, y + s * i * dy)) == c: cells.append((x + s * i * dx, y + s * i * dy)) i += 1 # Standard Gomoku wins on ANY exact five, even when another axis is an overline. if len(cells) == 5: return 5, sorted(cells) if len(cells) > best: best, line = len(cells), sorted(cells) return best, line def match(brains, opening, size=15, turn_ms=1000): """brains: two (argv, cwd); the first plays black; the next colour follows the opening parity. Returns the replay.""" live = [] board, moves, out = {}, [], {'winner': None, 'reason': 'board full', 'five': None} try: for i, config in enumerate(brains): try: b = Brain(*config) live.append(b) b.send(f'START {size}', f'INFO timeout_turn {turn_ms}', 'INFO timeout_match 0', 'INFO rule 1') if not b.reply(5).upper().startswith('OK'): raise ValueError except (queue.Empty, ValueError, OSError): return {**base(size, opening, moves), 'winner': 1 - i, 'reason': 'did not start'} for i, (x, y) in enumerate(opening): board[(x, y)] = i % 2 moves.append([x, y, 0]) side = len(opening) % 2 told = [False, False] while True: t = time.monotonic() try: if not told[side]: if moves: live[side].send('BOARD', *[f'{a},{b},{1 if board[(a, b)] == side else 2}' for a, b, _ in moves], 'DONE') else: live[side].send('BEGIN') told[side] = True else: live[side].send(f'TURN {x},{y}') x, y = map(int, live[side].reply(turn_ms / 1000).split(',')) except (queue.Empty, ValueError, OSError): out = {'winner': 1 - side, 'reason': 'out of time or no move', 'five': None} break if not (0 <= x < size and 0 <= y < size) or (x, y) in board: out = {'winner': 1 - side, 'reason': f'illegal move {x},{y}', 'five': None} break board[(x, y)] = side moves.append([x, y, int((time.monotonic() - t) * 1000)]) n, line = run_of(board, x, y, side) if n == 5: out = {'winner': side, 'reason': 'five', 'five': line} break if len(board) == size * size: break side = 1 - side finally: for b in live: try: b.send('END') b.p.wait(1) except Exception: b.p.kill() b.p.wait() finally: try: b.p.stdin.close() except OSError: pass b.p.stdout.close() return {**base(size, opening, moves), **out} def base(size, opening, moves): return {'game': 'gomoku', 'rule': 'standard', 'size': size, 'opening': len(opening), 'moves': moves}