游戏
运行代码后,点击"Enable AI Opponent"按钮,AI将作为白棋自动下棋。
玩家作为黑棋,点击棋盘落子。
AI会根据当前棋盘局势自动选择落子位置。
界面
代码
import tkinter as tk
from tkinter import messagebox
BOARD_SIZE = 15
CELL_SIZE = 40
STONE_RADIUS = 15
BOARD_COLOR = "#DEB887"
class Gomoku:
def __init__(self, root):
self.root = root
self.root.title("Gomoku")
self.root.resizable(False, False)
self.board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] # 0: empty, 1: black, 2: white
self.is_black_turn = True # Black goes first
self.ai_enabled = False # Whether AI opponent is enabled
self.canvas = tk.Canvas(root, width=BOARD_SIZE * CELL_SIZE, height=BOARD_SIZE * CELL_SIZE, bg=BOARD_COLOR)
self.canvas.pack()
self.draw_board()
self.canvas.bind("<Button-1>", self.on_mouse_click)
# Add AI toggle button
self.ai_button = tk.Button(root, text="Enable AI Opponent", command=self.toggle_ai)
self.ai_button.pack()
def draw_board(self):
self.canvas.delete("all")
for i in range(BOARD_SIZE):
self.canvas.create_line(0, i * CELL_SIZE, BOARD_SIZE * CELL_SIZE, i * CELL_SIZE) # Draw horizontal lines
self.canvas.create_line(i * CELL_SIZE, 0, i * CELL_SIZE, BOARD_SIZE * CELL_SIZE) # Draw vertical lines
for<