import tkinter as tk
from tkinter import messagebox
import random

class TicTacToeAI:
    def __init__(self, root):
        self.root = root
        self.root.title("井字棋 - AI对战")
        self.root.geometry("360x420")
        self.root.resizable(False, False)

        # 棋盘数据 9格 0空，1玩家X，2AI O
        self.board = [0 for _ in range(9)]
        self.player = 1
        self.ai = 2
        self.game_over = False

        # 标题
        tk.Label(root, text="井字棋（你 X | AI O）", font=("Arial",16)).pack(pady=10)

        self.buttons = []
        frame = tk.Frame(root)
        frame.pack()

        # 创建3x3按钮棋盘
        for i in range(9):
            btn = tk.Button(frame, width=5, height=2, font=("Arial",22),
                            command=lambda idx=i: self.player_click(idx))
            btn.grid(row=i//3, column=i%3)
            self.buttons.append(btn)

        # 重置按钮
        tk.Button(root, text="重新开局", command=self.reset_game, font=("Arial",12)).pack(pady=15)

    def check_win(self, check_player):
        # 所有获胜组合
        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:
            if self.board[line[0]] == check_player and self.board[line[1]] == check_player and self.board[line[2]] == check_player:
                return True
        return False

    def is_full(self):
        return all(x != 0 for x in self.board)

    def player_click(self, index):
        if self.game_over or self.board[index] != 0:
            return
        # 玩家落子
        self.board[index] = self.player
        self.buttons[index].config(text="X")

        if self.check_win(self.player):
            self.game_over = True
            messagebox.showinfo("结果", "恭喜！你战胜AI！")
            return
        if self.is_full():
            self.game_over = True
            messagebox.showinfo("结果", "平局！")
            return

        # AI思考落子
        self.ai_move()

    def ai_move(self):
        # AI简易策略
        move = self.find_best_move()
        self.board[move] = self.ai
        self.buttons[move].config(text="O")

        if self.check_win(self.ai):
            self.game_over = True
            messagebox.showinfo("结果", "AI获胜，再接再厉！")
            return
        if self.is_full():
            self.game_over = True
            messagebox.showinfo("结果", "平局！")

    def find_best_move(self):
        # 1. AI能直接赢，优先走
        for i in range(9):
            if self.board[i] == 0:
                self.board[i] = self.ai
                if self.check_win(self.ai):
                    self.board[i] = 0
                    return i
                self.board[i] = 0
        # 2. 阻止玩家获胜
        for i in range(9):
            if self.board[i] == 0:
                self.board[i] = self.player
                if self.check_win(self.player):
                    self.board[i] = 0
                    return i
                self.board[i] = 0
        # 3. 占中心
        if self.board[4] == 0:
            return 4
        # 4. 随机空位
        empty = [i for i, val in enumerate(self.board) if val == 0]
        return random.choice(empty)

    def reset_game(self):
        self.board = [0]*9
        self.game_over = False
        for btn in self.buttons:
            btn.config(text="")

if __name__ == "__main__":
    win = tk.Tk()
    app = TicTacToeAI(win)
    win.mainloop()