"""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 balanced 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 queue, subprocess, threading, time D = [(1, 0), (0, 1), (1, 1), (1, -1)] class Brain: def __init__(self, argv, cwd): self.p = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1) 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: # MESSAGE, DEBUG and SUGGEST lines are the brain talking, not moving l = self.q.get(timeout=max(0.001, end - time.monotonic())).strip() if l.split(' ')[0].upper() not in ('MESSAGE', 'DEBUG', 'SUGGEST'): return l 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 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 (moves first after the opening). Returns the replay.""" live = [Brain(*b) for b in brains] board, moves, out = {}, [], {'winner': None, 'reason': 'board full', 'five': None} try: for b in live: b.send(f'START {size}', f'INFO timeout_turn {turn_ms}', 'INFO timeout_match 0', 'INFO rule 1') for i, b in enumerate(live): try: if not b.reply(5).upper().startswith('OK'): raise ValueError except (queue.Empty, ValueError): 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 if opening: # the side to move learns the opening by BOARD (1 its own stones, 2 the other's) live[side].send('BOARD', *[f'{x},{y},{1 if board[(x, y)] == side else 2}' for x, y, _ in moves], 'DONE') else: live[side].send('BEGIN') told = [side == s or not opening for s in (0, 1)] while True: t = time.monotonic() try: x, y = map(int, live[side].reply(turn_ms / 1000 + 0.5).split(',')) except (queue.Empty, ValueError): 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 if not told[side]: live[side].send('BOARD', *[f'{a},{b},{1 if board[(a, b)] == side else 2}' for a, b, _ in moves], 'DONE') told[side] = True else: live[side].send(f'TURN {x},{y}') finally: for b in live: try: b.send('END') b.p.wait(1) except Exception: b.p.kill() return {**base(size, opening, moves), **out} def base(size, opening, moves): return {'game': 'gomoku', 'rule': 'standard', 'size': size, 'opening': len(opening), 'moves': moves}