| 1 | """A Gomocup match between two brains, as Piskvork runs one: the brains speak the Gomocup protocol on stdin and stdout |
| 2 | (START, INFO, BEGIN, TURN, BOARD ... DONE, END), the board is 15x15 and the rule is standard: exactly five in a row wins, |
| 3 | an overline does not. A match starts from a fixed opening of a few stones and is played twice with colours swapped, |
| 4 | as Gomocup does. A brain that runs out of time, answers nonsense or plays on a stone loses. Renju's forbidden moves are |
| 5 | not judged (ponytail: standard rule only; renju needs its own detector, the free ones are GPL). |
| 6 | """ |
| 7 | import os, queue, subprocess, threading, time |
| 8 | |
| 9 | D = [(1, 0), (0, 1), (1, 1), (1, -1)] |
| 10 | |
| 11 | |
| 12 | class Brain: |
| 13 | def __init__(self, argv, cwd): |
| 14 | env = {k: v for k, v in os.environ.items() if not k.startswith(('SS_', 'SLURM_'))} |
| 15 | self.p = subprocess.Popen(argv, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, env=env) |
| 16 | self.q = queue.Queue() |
| 17 | threading.Thread(target=lambda: [self.q.put(l) for l in self.p.stdout], daemon=True).start() |
| 18 | |
| 19 | def send(self, *lines): |
| 20 | self.p.stdin.write(''.join(l + '\n' for l in lines)) |
| 21 | self.p.stdin.flush() |
| 22 | |
| 23 | def reply(self, timeout): |
| 24 | end = time.monotonic() + timeout |
| 25 | while True: |
| 26 | remaining = end - time.monotonic() |
| 27 | if remaining <= 0: |
| 28 | raise queue.Empty |
| 29 | line = self.q.get(timeout=remaining).strip() |
| 30 | cmd, _, arg = line.partition(' ') |
| 31 | if cmd.upper() == 'SUGGEST': |
| 32 | self.send(f'PLAY {arg}') |
| 33 | elif line and cmd.upper() not in ('MESSAGE', 'DEBUG'): |
| 34 | return line |
| 35 | |
| 36 | |
| 37 | def run_of(board, x, y, c): |
| 38 | best, line = 0, None |
| 39 | for dx, dy in D: |
| 40 | cells = [(x, y)] |
| 41 | for s in (1, -1): |
| 42 | i = 1 |
| 43 | while board.get((x + s * i * dx, y + s * i * dy)) == c: |
| 44 | cells.append((x + s * i * dx, y + s * i * dy)) |
| 45 | i += 1 |
| 46 | |
| 47 | if len(cells) == 5: |
| 48 | return 5, sorted(cells) |
| 49 | if len(cells) > best: |
| 50 | best, line = len(cells), sorted(cells) |
| 51 | return best, line |
| 52 | |
| 53 | |
| 54 | def match(brains, opening, size=15, turn_ms=1000): |
| 55 | """brains: two (argv, cwd); the first plays black; the next colour follows the opening parity. Returns the replay.""" |
| 56 | live = [] |
| 57 | board, moves, out = {}, [], {'winner': None, 'reason': 'board full', 'five': None} |
| 58 | try: |
| 59 | for i, config in enumerate(brains): |
| 60 | try: |
| 61 | b = Brain(*config) |
| 62 | live.append(b) |
| 63 | b.send(f'START {size}', f'INFO timeout_turn {turn_ms}', 'INFO timeout_match 0', 'INFO rule 1') |
| 64 | if not b.reply(5).upper().startswith('OK'): |
| 65 | raise ValueError |
| 66 | except (queue.Empty, ValueError, OSError): |
| 67 | return {**base(size, opening, moves), 'winner': 1 - i, 'reason': 'did not start'} |
| 68 | for i, (x, y) in enumerate(opening): |
| 69 | board[(x, y)] = i % 2 |
| 70 | moves.append([x, y, 0]) |
| 71 | side = len(opening) % 2 |
| 72 | told = [False, False] |
| 73 | while True: |
| 74 | t = time.monotonic() |
| 75 | try: |
| 76 | if not told[side]: |
| 77 | if moves: |
| 78 | live[side].send('BOARD', *[f'{a},{b},{1 if board[(a, b)] == side else 2}' for a, b, _ in moves], 'DONE') |
| 79 | else: |
| 80 | live[side].send('BEGIN') |
| 81 | told[side] = True |
| 82 | else: |
| 83 | live[side].send(f'TURN {x},{y}') |
| 84 | x, y = map(int, live[side].reply(turn_ms / 1000).split(',')) |
| 85 | except (queue.Empty, ValueError, OSError): |
| 86 | out = {'winner': 1 - side, 'reason': 'out of time or no move', 'five': None} |
| 87 | break |
| 88 | if not (0 <= x < size and 0 <= y < size) or (x, y) in board: |
| 89 | out = {'winner': 1 - side, 'reason': f'illegal move {x},{y}', 'five': None} |
| 90 | break |
| 91 | board[(x, y)] = side |
| 92 | moves.append([x, y, int((time.monotonic() - t) * 1000)]) |
| 93 | n, line = run_of(board, x, y, side) |
| 94 | if n == 5: |
| 95 | out = {'winner': side, 'reason': 'five', 'five': line} |
| 96 | break |
| 97 | if len(board) == size * size: |
| 98 | break |
| 99 | side = 1 - side |
| 100 | finally: |
| 101 | for b in live: |
| 102 | try: |
| 103 | b.send('END') |
| 104 | b.p.wait(1) |
| 105 | except Exception: |
| 106 | b.p.kill() |
| 107 | b.p.wait() |
| 108 | finally: |
| 109 | try: |
| 110 | b.p.stdin.close() |
| 111 | except OSError: |
| 112 | pass |
| 113 | b.p.stdout.close() |
| 114 | return {**base(size, opening, moves), **out} |
| 115 | |
| 116 | |
| 117 | def base(size, opening, moves): |
| 118 | return {'game': 'gomoku', 'rule': 'standard', 'size': size, 'opening': len(opening), 'moves': moves} |