import tkinter as tk
from tkinter import messagebox
import random

class TicTacToe:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("井字棋 VS AI")
        # 棋盘状态
        self.board = [""] * 9
        self.player_char = "X"
        self.ai_char = "O"
        self.is_game_over = False
        self.button_list = []
        self.build_gui()

    def build_gui(self):
        # 生成3×3棋盘按钮
        for index in range(9):
            btn = tk.Button(
                self.root,
                text="",
                font=("SimHei", 32, "bold"),
                width=4,
                height=2,
                command=lambda i=index: self.on_click(i)
            )
            btn.grid(row=index // 3, column=index % 3)
            self.button_list.append(btn)

        # 重置按钮
        reset_btn = tk.Button(
            self.root,
            text="重新开局",
            font=("SimHei", 12),
            command=self.restart
        )
        reset_btn.grid(row=3, column=0, columnspan=3, pady=8)

    def on_click(self, pos):
        """玩家点击棋盘"""
        if self.is_game_over or self.board[pos] != "":
            return
        # 玩家落子
        self.board[pos] = self.player_char
        self.button_list[pos]["text"] = self.player_char
        self.check_game_status()
        if not self.is_game_over:
            # 延迟执行AI落子，模拟思考
            self.root.after(350, self.ai_play)

    def ai_play(self):
        """AI自动落子逻辑"""
        win_pos = self.search_win_pos(self.ai_char)
        if win_pos is None:
            win_pos = self.search_win_pos(self.player_char)
        if win_pos is None:
            # 随机选空位
            empty_slots = [i for i, val in enumerate(self.board) if val == ""]
            win_pos = random.choice(empty_slots)

        self.board[win_pos] = self.ai_char
        self.button_list[win_pos]["text"] = self.ai_char
        self.check_game_status()

    def search_win_pos(self, symbol):
        """查找能直接获胜的空位"""
        win_lines = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ]
        for line in win_lines:
            a, b, c = line
            cells = [self.board[a], self.board[b], self.board[c]]
            if cells.count(symbol) == 2 and cells.count("") == 1:
                if self.board[a] == "":
                    return a
                elif self.board[b] == "":
                    return b
                else:
                    return c
        return None

    def check_game_status(self):
        """检测胜负和平局"""
        win_lines = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ]
        # 判断胜利
        for line in win_lines:
            i1, i2, i3 = line
            if self.board[i1] == self.board[i2] == self.board[i3] != "":
                self.is_game_over = True
                winner = self.board[i1]
                if winner == self.player_char:
                    messagebox.showinfo("结果", "你战胜AI啦！")
                else:
                    messagebox.showinfo("结果", "AI赢了！")
                return
        # 判断平局
        if all(cell != "" for cell in self.board):
            self.is_game_over = True
            messagebox.showinfo("结果", "本局平局！")

    def restart(self):
        """重置游戏"""
        self.board = [""] * 9
        self.is_game_over = False
        for btn in self.button_list:
            btn["text"] = ""

    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    game = TicTacToe()
    game.run()