File size: 16,001 Bytes
e26350a
 
 
f5a33e6
 
 
e26350a
 
 
 
 
 
 
 
 
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
 
 
 
 
 
f5a33e6
e26350a
f5a33e6
e26350a
 
 
 
 
 
f5a33e6
e26350a
 
f5a33e6
 
 
 
 
 
 
 
e26350a
f5a33e6
 
 
 
 
 
 
 
 
e26350a
 
 
 
 
 
 
f5a33e6
 
 
 
 
e26350a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a33e6
e26350a
 
 
 
 
f5a33e6
e26350a
 
 
 
f5a33e6
e26350a
 
f5a33e6
 
 
 
e26350a
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
 
 
f5a33e6
e26350a
 
 
 
 
 
f5a33e6
e26350a
 
f5a33e6
 
e26350a
f5a33e6
e26350a
f5a33e6
 
e26350a
f5a33e6
e26350a
f5a33e6
 
 
 
 
 
 
 
 
 
 
e26350a
 
 
 
 
f5a33e6
 
e26350a
 
 
 
 
f5a33e6
 
e26350a
 
 
f5a33e6
 
 
 
 
 
 
 
e26350a
f5a33e6
e26350a
 
f5a33e6
 
e26350a
 
f5a33e6
 
e26350a
 
f5a33e6
 
 
 
 
 
e26350a
 
 
 
 
 
 
 
 
 
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
e26350a
 
 
 
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26350a
 
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
e26350a
f5a33e6
 
 
 
 
 
 
 
 
 
 
 
e26350a
 
 
f5a33e6
e26350a
f5a33e6
e26350a
 
f5a33e6
 
e26350a
 
f5a33e6
 
 
e26350a
f5a33e6
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import gradio as gr
from PIL import Image, ImageDraw
import numpy as np
import math
from io import BytesIO
import base64

# Constants
BOARD_SIZE = 9
CELL_SIZE = 50
PIECE_RADIUS = 20
EMPTY = 0
WHITE_SOLDIER = 1
BLACK_SOLDIER = 2
KING = 3
CASTLE = (4, 4)  # Center of the 9x9 board (0-based indices)
CAMPS = [
    (0,3), (0,4), (0,5), (1,4),  # Top camp
    (8,3), (8,4), (8,5), (7,4),  # Bottom camp
    (3,0), (4,0), (5,0), (4,1),  # Left camp
    (3,8), (4,8), (5,8), (4,7)   # Right camp
]
ESCAPES = [(i,j) for i in [0,8] for j in range(BOARD_SIZE)] + [(i,j) for j in [0,8] for i in range(BOARD_SIZE) if (i,j) not in CAMPS]
COLORS = {
    'empty': '#FFFFFF',  # White for regular empty cells
    'castle': '#808080',  # Gray for castle
    'camp': '#A0522D',    # Brown for camps
    'escape': '#00FF00',  # Green for escape tiles
    'white': '#FFFFFF',   # White for white soldiers
    'black': '#000000',   # Black for black soldiers
    'king': '#FFD700',    # Gold for king
    'highlight': '#FFFF00' # Yellow for selected cell
}

# Game state class
class TablutState:
    def __init__(self):
        self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
        self.turn = 'WHITE'
        self.black_in_camps = set(CAMPS)  # Track black pieces in camps
        self.setup_initial_position()
        self.move_history = []  # To detect draws

    def setup_initial_position(self):
        self.board[4, 4] = KING
        white_positions = [(3,4), (4,3), (4,5), (5,4), (2,4), (4,2), (4,6), (6,4)]
        for pos in white_positions:
            self.board[pos] = WHITE_SOLDIER
        for pos in CAMPS:
            self.board[pos] = BLACK_SOLDIER

    def copy(self):
        new_state = TablutState()
        new_state.board = self.board.copy()
        new_state.turn = self.turn
        new_state.black_in_camps = self.black_in_camps.copy()
        new_state.move_history = self.move_history.copy()
        return new_state

# Utility functions
def pos_to_coord(pos):
    """Convert (row, col) to board coordinate (e.g., (4,4) -> 'E5')."""
    row, col = pos
    return f"{chr(ord('A') + col)}{row + 1}"

def coord_to_pos(coord):
    """Convert board coordinate (e.g., 'E5') to (row, col)."""
    col = ord(coord[0].upper()) - ord('A')
    row = int(coord[1]) - 1
    return (row, col)

def is_adjacent_to_castle(pos):
    x, y = pos
    cx, cy = CASTLE
    return (abs(x - cx) == 1 and y == cy) or (abs(y - cy) == 1 and x == cx)

def get_friendly_pieces(turn):
    return [WHITE_SOLDIER, KING] if turn == 'WHITE' else [BLACK_SOLDIER]

def manhattan_distance(pos1, pos2):
    return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])

# Game logic functions
def is_valid_move(state, from_pos, to_pos):
    if from_pos == to_pos:
        return False
    piece = state.board[from_pos]
    if state.turn == 'WHITE' and piece not in [WHITE_SOLDIER, KING]:
        return False
    if state.turn == 'BLACK' and piece != BLACK_SOLDIER:
        return False
    if state.board[to_pos] != EMPTY:
        return False
    from_row, from_col = from_pos
    to_row, to_col = to_pos
    if from_row != to_row and from_col != to_col:
        return False
    # Path must be clear
    if from_row == to_row:
        step = 1 if to_col > from_col else -1
        for col in range(from_col + step, to_col, step):
            if state.board[from_row, col] != EMPTY:
                return False
    else:
        step = 1 if to_row > from_row else -1
        for row in range(from_row + step, to_row, step):
            if state.board[row, from_col] != EMPTY:
                return False
    # Castle is only for the king
    if to_pos == CASTLE and piece != KING:
        return False
    # Camp restrictions
    if to_pos in CAMPS:
        if state.turn == 'WHITE' or (state.turn == 'BLACK' and from_pos not in state.black_in_camps):
            return False
    return True

def get_legal_moves(state, from_pos):
    piece = state.board[from_pos]
    if not piece or (state.turn == 'WHITE' and piece not in [WHITE_SOLDIER, KING]) or \
       (state.turn == 'BLACK' and piece != BLACK_SOLDIER):
        return []
    row, col = from_pos
    moves = []
    for r in range(BOARD_SIZE):
        if r != row:
            to_pos = (r, col)
            if is_valid_move(state, from_pos, to_pos):
                moves.append(to_pos)
    for c in range(BOARD_SIZE):
        if c != col:
            to_pos = (row, c)
            if is_valid_move(state, from_pos, to_pos):
                moves.append(to_pos)
    return moves

def is_soldier_captured(state, pos, friendly):
    x, y = pos
    friendly_pieces = get_friendly_pieces(friendly)
    # Standard capture
    if y > 0 and y < BOARD_SIZE - 1:
        if state.board[x, y-1] in friendly_pieces and state.board[x, y+1] in friendly_pieces:
            return True
    if x > 0 and x < BOARD_SIZE - 1:
        if state.board[x-1, y] in friendly_pieces and state.board[x+1, y] in friendly_pieces:
            return True
    # Capture against castle or camp
    if is_adjacent_to_castle(pos):
        cx, cy = CASTLE
        if x == cx:
            if y < cy and y > 0 and state.board[x, y-1] in friendly_pieces:
                return True
            elif y > cy and y < BOARD_SIZE - 1 and state.board[x, y+1] in friendly_pieces:
                return True
        elif y == cy:
            if x < cx and x > 0 and state.board[x-1, y] in friendly_pieces:
                return True
            elif x > cx and x < BOARD_SIZE - 1 and state.board[x+1, y] in friendly_pieces:
                return True
    if pos in CAMPS:
        return False  # Cannot capture pieces in camps
    for camp in CAMPS:
        if pos == (camp[0] + 1, camp[1]) and state.board[camp] in friendly_pieces + [EMPTY]:
            return False
        elif pos == (camp[0] - 1, camp[1]) and state.board[camp] in friendly_pieces + [EMPTY]:
            return False
        elif pos == (camp[0], camp[1] + 1) and state.board[camp] in friendly_pieces + [EMPTY]:
            return False
        elif pos == (camp[0], camp[1] - 1) and state.board[camp] in friendly_pieces + [EMPTY]:
            return False
    return False

def is_king_captured(state, pos):
    x, y = pos
    if pos == CASTLE:
        return all(state.board[x + dx, y + dy] == BLACK_SOLDIER for dx, dy in [(-1,0), (1,0), (0,-1), (0,1)]
                   if 0 <= x + dx < BOARD_SIZE and 0 <= y + dy < BOARD_SIZE)
    elif is_adjacent_to_castle(pos):
        cx, cy = CASTLE
        dx = cx - x
        dy = cy - y
        free_directions = [d for d in [(-1,0), (1,0), (0,-1), (0,1)] if d != (dx, dy)]
        return all(state.board[x + d[0], y + d[1]] == BLACK_SOLDIER for d in free_directions
                   if 0 <= x + d[0] < BOARD_SIZE and 0 <= y + d[1] < BOARD_SIZE)
    else:
        return is_soldier_captured(state, pos, 'BLACK')

def apply_move(state, from_pos, to_pos):
    new_state = state.copy()
    piece = new_state.board[from_pos]
    new_state.board[to_pos] = piece
    new_state.board[from_pos] = EMPTY
    if new_state.turn == 'BLACK' and from_pos in new_state.black_in_camps and to_pos not in CAMPS:
        new_state.black_in_camps.discard(from_pos)
    # Apply captures
    captures = []
    opponent = 'BLACK' if new_state.turn == 'WHITE' else 'WHITE'
    for x in range(BOARD_SIZE):
        for y in range(BOARD_SIZE):
            if new_state.board[x, y] == (WHITE_SOLDIER if opponent == 'WHITE' else BLACK_SOLDIER):
                if is_soldier_captured(new_state, (x, y), new_state.turn):
                    captures.append((x, y))
    if opponent == 'WHITE':
        king_pos = find_king_position(new_state)
        if king_pos and is_king_captured(new_state, king_pos):
            captures.append(king_pos)
    for pos in captures:
        new_state.board[pos] = EMPTY
    new_state.turn = 'BLACK' if new_state.turn == 'WHITE' else 'WHITE'
    # Update move history for draw detection
    board_tuple = tuple(new_state.board.flatten())
    new_state.move_history.append(board_tuple)
    return new_state

def find_king_position(state):
    for x in range(BOARD_SIZE):
        for y in range(BOARD_SIZE):
            if state.board[x, y] == KING:
                return (x, y)
    return None

def check_game_status(state):
    king_pos = find_king_position(state)
    if king_pos is None:
        return "BLACK WINS"
    if king_pos in ESCAPES:
        return "WHITE WINS"
    # Check for no legal moves
    pieces = []
    for x in range(BOARD_SIZE):
        for y in range(BOARD_SIZE):
            if (state.turn == 'WHITE' and state.board[x, y] in [WHITE_SOLDIER, KING]) or \
               (state.turn == 'BLACK' and state.board[x, y] == BLACK_SOLDIER):
                pieces.append((x, y))
    has_moves = False
    for pos in pieces:
        if get_legal_moves(state, pos):
            has_moves = True
            break
    if not has_moves:
        return "BLACK WINS" if state.turn == 'WHITE' else "WHITE WINS"
    # Check for draw (same state twice)
    board_tuple = tuple(state.board.flatten())
    if state.move_history.count(board_tuple) >= 2:
        return "DRAW"
    return "CONTINUE"

# AI implementation
def evaluate_state(state):
    status = check_game_status(state)
    if status == "WHITE WINS":
        return 1000
    elif status == "BLACK WINS":
        return -1000
    elif status == "DRAW":
        return 0
    king_pos = find_king_position(state)
    if not king_pos:
        return -1000
    # Heuristic: distance from king to nearest escape
    min_escape_dist = min(manhattan_distance(king_pos, e) for e in ESCAPES)
    white_pieces = sum(1 for x in range(BOARD_SIZE) for y in range(BOARD_SIZE) if state.board[x, y] == WHITE_SOLDIER)
    black_pieces = sum(1 for x in range(BOARD_SIZE) for y in range(BOARD_SIZE) if state.board[x, y] == BLACK_SOLDIER)
    # Encourage Black to surround king, White to escape
    if state.turn == 'WHITE':
        return -min_escape_dist * 10 + white_pieces * 5 - black_pieces * 3
    else:
        return min_escape_dist * 10 - white_pieces * 3 + black_pieces * 5

def minimax(state, depth, alpha, beta, maximizing_player):
    if depth == 0 or check_game_status(state) != "CONTINUE":
        return evaluate_state(state), None
    if maximizing_player:
        max_eval = -math.inf
        best_move = None
        pieces = [(x, y) for x in range(BOARD_SIZE) for y in range(BOARD_SIZE) if state.board[x, y] == BLACK_SOLDIER]
        for from_pos in pieces:
            for to_pos in get_legal_moves(state, from_pos):
                new_state = apply_move(state, from_pos, to_pos)
                eval_score, _ = minimax(new_state, depth - 1, alpha, beta, False)
                if eval_score > max_eval:
                    max_eval = eval_score
                    best_move = (from_pos, to_pos)
                alpha = max(alpha, eval_score)
                if beta <= alpha:
                    break
        return max_eval, best_move
    else:
        min_eval = math.inf
        best_move = None
        pieces = [(x, y) for x in range(BOARD_SIZE) for y in range(BOARD_SIZE) if state.board[x, y] in [WHITE_SOLDIER, KING]]
        for from_pos in pieces:
            for to_pos in get_legal_moves(state, from_pos):
                new_state = apply_move(state, from_pos, to_pos)
                eval_score, _ = minimax(new_state, depth - 1, alpha, beta, True)
                if eval_score < min_eval:
                    min_eval = eval_score
                    best_move = (from_pos, to_pos)
                beta = min(beta, eval_score)
                if beta <= alpha:
                    break
        return min_eval, best_move

def ai_move(state):
    if state.turn != 'BLACK':
        return state, "Not AI's turn", None
    depth = 3  # Adjustable for performance
    _, move = minimax(state, depth, -math.inf, math.inf, True)
    if move:
        from_pos, to_pos = move
        new_state = apply_move(state, from_pos, to_pos)
        return new_state, f"AI moved from {pos_to_coord(from_pos)} to {pos_to_coord(to_pos)}", None
    return state, "AI has no moves", None

# SVG board generation
def generate_board_svg(state, selected_pos=None):
    width = BOARD_SIZE * CELL_SIZE
    height = BOARD_SIZE * CELL_SIZE
    svg = [f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">']
    # Draw cells
    for x in range(BOARD_SIZE):
        for y in range(BOARD_SIZE):
            pos = (x, y)
            fill = COLORS['empty']
            if pos == CASTLE:
                fill = COLORS['castle']
            elif pos in CAMPS:
                fill = COLORS['camp']
            elif pos in ESCAPES:
                fill = COLORS['escape']
            if pos == selected_pos:
                fill = COLORS['highlight']
            svg.append(f'<rect x="{y * CELL_SIZE}" y="{x * CELL_SIZE}" width="{CELL_SIZE}" height="{CELL_SIZE}" fill="{fill}" stroke="black" stroke-width="1"/>')
    # Draw pieces
    for x in range(BOARD_SIZE):
        for y in range(BOARD_SIZE):
            piece = state.board[x, y]
            if piece != EMPTY:
                cx = y * CELL_SIZE + CELL_SIZE // 2
                cy = x * CELL_SIZE + CELL_SIZE // 2
                color = COLORS['white'] if piece == WHITE_SOLDIER else COLORS['black'] if piece == BLACK_SOLDIER else COLORS['king']
                svg.append(f'<circle cx="{cx}" cy="{cy}" r="{PIECE_RADIUS}" fill="{color}" stroke="black" stroke-width="1"/>')
    # Draw grid labels
    for i in range(BOARD_SIZE):
        svg.append(f'<text x="5" y="{i * CELL_SIZE + CELL_SIZE // 2 + 5}" fill="black">{BOARD_SIZE - i}</text>')
        svg.append(f'<text x="{i * CELL_SIZE + CELL_SIZE // 2 - 5}" y="{height - 10}" fill="black">{chr(ord("A") + i)}</text>')
    svg.append('</svg>')
    return ''.join(svg)

def svg_to_image(svg_content):
    img = Image.new('RGB', (BOARD_SIZE * CELL_SIZE, BOARD_SIZE * CELL_SIZE), color='white')
    # For Gradio, we encode SVG as base64 to display in HTML
    svg_bytes = svg_content.encode('utf-8')
    svg_base64 = base64.b64encode(svg_bytes).decode('utf-8')
    return svg_base64

# Gradio interface functions
def click_board(state, selected_pos, evt: gr.SelectData):
    if state.turn != 'WHITE':
        return state, "It's the AI's turn", None, selected_pos
    x = evt.index[1] // CELL_SIZE
    y = evt.index[0] // CELL_SIZE
    pos = (x, y)
    if selected_pos is None:
        # Select a piece
        if state.board[pos] in [WHITE_SOLDIER, KING]:
            return state, f"Selected {pos_to_coord(pos)}", None, pos
        else:
            return state, "Select a White piece or King", None, None
    else:
        # Try to move
        if is_valid_move(state, selected_pos, pos):
            new_state = apply_move(state, selected_pos, pos)
            status = check_game_status(new_state)
            if status != "CONTINUE":
                return new_state, status, None, None
            # Trigger AI move
            ai_state, ai_message, _ = ai_move(new_state)
            final_status = check_game_status(ai_state)
            return ai_state, f"Your move to {pos_to_coord(pos)}. {ai_message}. {final_status if final_status != 'CONTINUE' else ''}", None, None
        else:
            return state, "Invalid move", None, None

def new_game():
    state = TablutState()
    return state, "New game started. Your turn (White).", generate_board_svg(state), None

# Gradio interface
with gr.Blocks(title="Tablut Game") as demo:
    state = gr.State()
    selected_pos = gr.State(value=None)
    board_html = gr.HTML(label="Board")
    message_label = gr.Label(label="Message")
    new_game_button = gr.Button("New Game")
    board_html.select(fn=click_board, inputs=[state, selected_pos], outputs=[state, message_label, board_html, selected_pos])
    new_game_button.click(fn=new_game, outputs=[state, message_label, board_html, selected_pos])
    demo.load(fn=new_game, outputs=[state, message_label, board_html, selected_pos])

# Note: demo.launch() is not needed for HF Spaces