|
import gradio as gr |
|
|
|
|
|
def initialize_board(): |
|
board = [[0 for _ in range(8)] for _ in range(8)] |
|
board[3][3], board[4][4] = 1, 1 |
|
board[3][4], board[4][3] = -1, -1 |
|
return board |
|
|
|
|
|
DIRECTIONS = [(-1, -1), (-1, 0), (-1, 1), |
|
(0, -1), (0, 1), |
|
(1, -1), (1, 0), (1, 1)] |
|
|
|
|
|
def get_flips(board, row, col, player): |
|
if board[row][col] != 0: |
|
return [] |
|
flips = [] |
|
for dr, dc in DIRECTIONS: |
|
r, c = row + dr, col + dc |
|
buffer = [] |
|
while 0 <= r < 8 and 0 <= c < 8 and board[r][c] == -player: |
|
buffer.append((r, c)) |
|
r += dr; c += dc |
|
if buffer and 0 <= r < 8 and 0 <= c < 8 and board[r][c] == player: |
|
flips.extend(buffer) |
|
return flips |
|
|
|
|
|
def apply_move(board, row, col, player): |
|
flips = get_flips(board, row, col, player) |
|
if not flips: |
|
return False |
|
board[row][col] = player |
|
for r, c in flips: |
|
board[r][c] = player |
|
return True |
|
|
|
|
|
def board_to_html(board): |
|
html = '<table style="border-collapse: collapse;">' |
|
for r in range(8): |
|
html += '<tr>' |
|
for c in range(8): |
|
cell = board[r][c] |
|
if cell == 1: |
|
color = 'white' |
|
elif cell == -1: |
|
color = 'black' |
|
else: |
|
color = 'transparent' |
|
html += f'<td style="width:40px;height:40px;border:1px solid #000;text-align:center;vertical-align:middle;background:{color};"></td>' |
|
html += '</tr>' |
|
html += '</table>' |
|
return html |
|
|
|
|
|
def count_score(board): |
|
black = sum(cell == -1 for row in board for cell in row) |
|
white = sum(cell == 1 for row in board for cell in row) |
|
return black, white |
|
|
|
|
|
def play_move(row, col, state): |
|
board, player = state |
|
row, col = int(row) - 1, int(col) - 1 |
|
if not (0 <= row < 8 and 0 <= col < 8): |
|
return board_to_html(board), f"Invalid position.", state |
|
if not apply_move(board, row, col, player): |
|
return board_to_html(board), "Invalid move.", state |
|
|
|
player = -player |
|
black_score, white_score = count_score(board) |
|
status = f"Black: {black_score} | White: {white_score} | {'Black' if player == -1 else 'White'} to move" |
|
return board_to_html(board), status, (board, player) |
|
|
|
|
|
def main(): |
|
with gr.Blocks() as demo: |
|
gr.HTML("<h2>Othello (Reversi) Game</h2>") |
|
board_html = gr.HTML(board_to_html(initialize_board())) |
|
status = gr.Text(value="Black: 2 | White: 2 | Black to move", interactive=False) |
|
with gr.Row(): |
|
row_input = gr.Slider(1, 8, step=1, label="Row") |
|
col_input = gr.Slider(1, 8, step=1, label="Column") |
|
submit = gr.Button("Place") |
|
state = gr.State((initialize_board(), -1)) |
|
submit.click(fn=play_move, |
|
inputs=[row_input, col_input, state], |
|
outputs=[board_html, status, state]) |
|
demo.launch() |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|