import tkinter as tk
import random
import math
import time

# ========================
# 全局变量（全部提前定义）
# ========================
BOARD_SIZE = 3
board = [[None for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = "X"
game_over = False
ai_difficulty = "medium"
first_move = "player"
player_symbol = "X"
ai_symbol = "O"

root = tk.Tk()
root.title("⭕❌ 井字棋 vs AI")
root.resizable(False, False)

canvas = tk.Canvas(root, width=300, height=300, highlightthickness=0)
canvas.pack()

panel = tk.Frame(root)
panel.pack(fill="x", pady=5)

score_label = tk.Label(panel, font=("Consolas", 11))
score_label.pack(side="left", padx=10)

status_label = tk.Label(root, font=("Consolas", 12))
status_label.pack()

# ========================
# 主题
# ========================
themes = {
    "🌸 樱花粉": {"bg": "#FFE4E9", "fg": "#D81B60", "line": "#F8BBD0"},
    "💙 天空蓝": {"bg": "#E3F2FD", "fg": "#1565C0", "line": "#90CAF9"},
    "💚 抹茶绿": {"bg": "#E8F5E9", "fg": "#2E7D32", "line": "#A5D6A7"},
    "🧡 蜜桔橙": {"bg": "#FFF3E0", "fg": "#EF6C00", "line": "#FFCC80"},
    "💜 梦幻紫": {"bg": "#F3E5F5", "fg": "#7B1FA2", "line": "#CE93D8"},
    "⚫ 极简黑": {"bg": "#212121", "fg": "#FFFFFF", "line": "#757575"},
}

def apply_theme(name):
    t = themes[name]
    root.configure(bg=t["bg"])
    panel.configure(bg=t["bg"])
    status_label.configure(bg=t["bg"], fg=t["fg"])
    score_label.configure(bg=t["bg"], fg=t["fg"])
    canvas.configure(background=t["bg"])
    draw_board()

for name in themes:
    tk.Button(
        panel, text=name, font=("Comic Sans MS", 8),
        command=lambda n=name: apply_theme(n)
    ).pack(side="left", padx=2)

# ========================
# 画棋盘
# ========================
def draw_board():
    canvas.delete("all")
    t = themes["🌸 樱花粉"]
    for i in range(1, BOARD_SIZE):
        canvas.create_line(i * 100, 0, i * 100, 300, fill=t["line"], width=3)
        canvas.create_line(0, i * 100, 300, i * 100, fill=t["line"], width=3)

    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if board[i][j]:
                x, y = j * 100 + 50, i * 100 + 50
                if board[i][j] == "X":
                    canvas.create_line(x - 30, y - 30, x + 30, y + 30, fill="#D32F2F", width=5)
                    canvas.create_line(x + 30, y - 30, x - 30, y + 30, fill="#D32F2F", width=5)
                else:
                    canvas.create_oval(x - 25, y - 25, x + 25, y + 25, fill="#1976D2", outline="")

# ========================
# 胜负判断
# ========================
def check_winner():
    for i in range(BOARD_SIZE):
        if board[i][0] == board[i][1] == board[i][2] and board[i][0]:
            return board[i][0]
        if board[0][i] == board[1][i] == board[2][i] and board[0][i]:
            return board[0][i]

    if board[0][0] == board[1][1] == board[2][2] and board[0][0]:
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] and board[0][2]:
        return board[0][2]

    if all(board[i][j] for i in range(BOARD_SIZE) for j in range(BOARD_SIZE)):
        return "draw"
    return None

# ========================
# AI 算法（Minimax）
# ========================
def minimax(b, player, depth):
    winner = check_winner_static(b)
    if winner == ai_symbol:
        return 10 - depth
    if winner == player_symbol:
        return depth - 10
    if winner == "draw":
        return 0

    scores = []
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if b[i][j] is None:
                b[i][j] = player
                score = minimax(b, ai_symbol if player == player_symbol else player_symbol, depth + 1)
                b[i][j] = None
                scores.append(score)

    return max(scores) if player == ai_symbol else min(scores)

def best_move():
    if ai_difficulty == "easy":
        empties = [(i, j) for i in range(BOARD_SIZE) for j in range(BOARD_SIZE) if board[i][j] is None]
        return random.choice(empties)

    if ai_difficulty == "medium" and random.random() < 0.3:
        empties = [(i, j) for i in range(BOARD_SIZE) for j in range(BOARD_SIZE) if board[i][j] is None]
        return random.choice(empties)

    best_score = -math.inf
    move = None
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if board[i][j] is None:
                board[i][j] = ai_symbol
                score = minimax(board, player_symbol, 0)
                board[i][j] = None
                if score > best_score:
                    best_score = score
                    move = (i, j)
    return move

def check_winner_static(b):
    for i in range(BOARD_SIZE):
        if b[i][0] == b[i][1] == b[i][2] and b[i][0]:
            return b[i][0]
        if b[0][i] == b[1][i] == b[2][i] and b[0][i]:
            return b[0][i]
    if b[0][0] == b[1][1] == b[2][2] and b[0][0]:
        return b[0][0]
    if b[0][2] == b[1][1] == b[2][0] and b[0][2]:
        return b[0][2]
    if all(b[i][j] for i in range(BOARD_SIZE) for j in range(BOARD_SIZE)):
        return "draw"
    return None

# ========================
# 点击逻辑（✅ global 在最前）
# ========================
def click_cell(i, j):
    global current_player, game_over

    if game_over or board[i][j] is not None:
        return
    if current_player != player_symbol:
        return

    board[i][j] = player_symbol
    draw_board()

    winner = check_winner()
    if winner:
        end_game(winner)
        return

    current_player = ai_symbol
    status_label.config(text="🤖 AI 思考中...")
    root.update()
    root.after(500, ai_turn)

# ========================
# AI 回合
# ========================
def ai_turn():
    global current_player, game_over

    if game_over:
        return

    move = best_move()
    if move:
        board[move[0]][move[1]] = ai_symbol
        draw_board()

    winner = check_winner()
    if winner:
        end_game(winner)
        return

    current_player = player_symbol
    status_label.config(text="⭕ 轮到你了 (X)")

# ========================
# 结束
# ========================
def end_game(winner):
    global game_over
    game_over = True
    if winner == "draw":
        status_label.config(text="🤝 平局！")
    elif winner == player_symbol:
        status_label.config(text="🎉 你赢了！")
    else:
        status_label.config(text="🤖 AI 赢了！")

# ========================
# 重置
# ========================
def reset_game():
    global board, current_player, game_over
    board = [[None for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    current_player = player_symbol if first_move == "player" else ai_symbol
    game_over = False
    draw_board()
    status_label.config(text="⭕ 轮到你了 (X)" if current_player == player_symbol else "🤖 AI 思考中...")
    if current_player == ai_symbol:
        root.after(500, ai_turn)

# ========================
# 绑定
# ========================
for i in range(BOARD_SIZE):
    for j in range(BOARD_SIZE):
        canvas.tag_bind(
            canvas.create_rectangle(j * 100, i * 100, (j + 1) * 100, (i + 1) * 100),
            "<Button-1>", lambda e, i=i, j=j: click_cell(i, j)
        )

tk.Button(panel, text="🔄 重开", command=reset_game).pack(side="right", padx=5)

for txt, diff in [("简单", "easy"), ("中等", "medium"), ("困难", "hard")]:
    tk.Button(panel, text=txt, command=lambda d=diff: setattr(sys.modules[__name__], 'ai_difficulty', d)).pack(side="left", padx=2)

# ========================
# 启动
# ========================
apply_theme("🌸 樱花粉")
reset_game()
root.mainloop()