import tkinter as tk
from tkinter import messagebox
import random

class TicTacToeAI:
    def __init__(self, window):
        self.win = window
        self.win.title("井字棋 VS AI")
        self.win.geometry("320x380")
        self.win.resizable(False, False)

        # 棋盘 9格，0空，1玩家X，2AI O
        self.board = [0] * 9
        self.buttons = []
        self.game_over = False

        # 标题
        tk.Label(self.win, text="你 X  | 电脑 O", font=("黑体", 16)).pack(pady=10)

        # 棋盘框架
        frame_board = tk.Frame(self.win)
        frame_board.pack()
        for i in range(9):
            btn = tk.Button(
                frame_board, text="", font=("黑体", 24),
                width=4, height=2, command=lambda idx=i: self.player_move(idx)
            )
            btn.grid(row=i//3, column=i%3)
            self.buttons.append(btn)

        # 重置按钮
        tk.Button(self.win, text="重新开局", command=self.reset_all, font=("黑体",12)).pack(pady=15)

    def player_move(self, index):
        # 游戏结束/格子已有棋子则不能点
        if self.game_over or self.board[index] != 0:
            return
        # 玩家落X
        self.board[index] = 1
        self.buttons[index].config(text="X", fg="#2277dd")
        self.check_result()
        if not self.game_over:
            # 玩家走完，AI落子
            self.ai_move()
            self.check_result()

    def ai_move(self):
        # AI简单策略：1.自己能赢直接走；2.堵住玩家赢；3.优先占角落；4.随便走
        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]            # 斜
        ]

        # 第一步：AI找可以一步胜利的位置
        for line in win_lines:
            a,b,c = line
            vals = [self.board[a], self.board[b], self.board[c]]
            if vals.count(2) == 2 and vals.count(0) == 1:
                blank = line[vals.index(0)]
                self.put_ai(blank)
                return

        # 第二步：堵玩家，玩家差一个就连线，AI占空位
        for line in win_lines:
            a,b,c = line
            vals = [self.board[a], self.board[b], self.board[c]]
            if vals.count(1) == 2 and vals.count(0) == 1:
                blank = line[vals.index(0)]
                self.put_ai(blank)
                return

        # 第三步：优先走四个角落
        corners = [0,2,6,8]
        empty_corner = [i for i in corners if self.board[i]==0]
        if empty_corner:
            self.put_ai(random.choice(empty_corner))
            return

        # 第四步：走中心，最后随便空格
        if self.board[4]==0:
            self.put_ai(4)
            return
        empty_all = [i for i in range(9) if self.board[i]==0]
        self.put_ai(random.choice(empty_all))

    def put_ai(self, idx):
        self.board[idx] = 2
        self.buttons[idx].config(text="O", fg="#dd2222")

    def check_result(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:
            a,b,c = line
            if self.board[a]==self.board[b]==self.board[c]!=0:
                self.game_over = True
                if self.board[a]==1:
                    messagebox.showinfo("结果", "恭喜，你赢了！")
                else:
                    messagebox.showinfo("结果", "AI获胜")
                return
        # 棋盘满了平局
        if 0 not in self.board:
            self.game_over = True
            messagebox.showinfo("结果", "平局！")

    def reset_all(self):
        # 全部重置为空
        self.board = [0]*9
        self.game_over = False
        for btn in self.buttons:
            btn.config(text="")

if __name__ == "__main__":
    root = tk.Tk()
    game = TicTacToeAI(root)
    root.mainloop()