File size: 2,208 Bytes
ab8fca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Lossless raw directional board context; no tactical scoring or move selection."""
import re

CONTEXT_LENGTH = 2048
SYSTEM = ('Play 15x15 Gomoku. X is you, O is the opponent, . is empty, # is outside. '
          'Each empty coordinate has four 9-cell raw lines: horizontal, vertical, '
          'diagonal down and diagonal up. Occupied cells are <coordinate:X/O>. '
          'Read the board and reply with one empty coordinate only.')
DIRECTIONS = [(1, 0), (0, 1), (1, 1), (1, -1)]


def validate_board(board):
    if not isinstance(board, list) or len(board) != 225 or any(type(v) is not int or v not in (0, 1, 2) for v in board):
        raise ValueError('board must contain 225 integers in {0, 1, 2}')


def coordinate(move):
    if type(move) is not int or not 0 <= move < 225:
        raise ValueError('invalid move index')
    return f'{chr(65+move % 15)}{move//15+1}'


def lines_at(board, move):
    x, y = move % 15, move//15
    return [''.join('.XO'[board[(y+k*dy)*15+x+k*dx]] if 0 <= x+k*dx < 15 and 0 <= y+k*dy < 15 else '#'
                    for k in range(-4, 5)) for dx, dy in DIRECTIONS]


def records(board):
    validate_board(board)
    return [f'<{coordinate(m)}:{".XO"[v]}>' if v else coordinate(m)+''.join('<line:'+line+'>' for line in lines_at(board, m))
            for m, v in enumerate(board)]


def board_text(board):
    cells = records(board)
    return '\n'.join(''.join(cells[y*15:(y+1)*15]) for y in range(15))+'\nYour move:'


def messages(board):
    return [{'role': 'system', 'content': SYSTEM}, {'role': 'user', 'content': board_text(board)}]


def parse_move(text, board):
    validate_board(board)
    match = re.fullmatch(r'([A-O])(1[0-5]|[1-9])', text.strip(), flags=re.IGNORECASE)
    if not match:
        raise ValueError('model did not generate exactly one coordinate')
    move = (int(match[2])-1)*15+ord(match[1].upper())-65
    if board[move]:
        raise ValueError('model selected an occupied cell')
    return move


def relative(board, player):
    validate_board(board)
    if type(player) is not int or player not in (1, 2):
        raise ValueError('player must be 1 or 2')
    return [0 if v == 0 else 1 if v == player else 2 for v in board]