import tkinter as tk
from tkinter import messagebox

game_state = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]
current_player = -1
buttons = []  # 将buttons定义在全局作用域


def check_win():
    for player in [-1, 1]:
        for i in range(3):
            if game_state[i][0] == player and game_state[i][1] == player and game_state[i][2] == player:
                return player
        for j in range(3):
            if game_state[0][j] == player and game_state[1][j] == player and game_state[2][j] == player:
                return player
        if game_state[0][0] == player and game_state[1][1] == player and game_state[2][2] == player:
            return player
        if game_state[0][2] == player and game_state[1][1] == player and game_state[2][0] == player:
            return player
    return 0


def make_move(row, col):
    global current_player
    if game_state[row][col] == 0:
        game_state[row][col] = current_player
        draw_mark(row, col, current_player)  # 使用自定义函数绘制标记
        current_player *= -1
        winner = check_win()
        if winner != 0:
            show_message(f"Player {get_mark(winner)} wins!")
            disable_buttons()


def get_mark(player):
    return "X" if player == -1 else "O"


def show_message(message):
    messagebox.showinfo("Tic Tac Toe", message)


def disable_buttons():
    for button in buttons:
        button.config(state="disabled")


def draw_mark(row, col, player):
    # 在canvas上绘制标记
    x = col * 100 + 50
    y = row * 100 + 50
    canvas.create_text(x, y, text=get_mark(player), font=("Arial", 50))


def create_ui(root):
    global canvas

    canvas = tk.Canvas(root, width=300, height=300)
    canvas.pack()

    for i in range(3):
        for j in range(3):
            x = j * 100
            y = i * 100
            b = tk.Button(root, text="", command=lambda row=i, col=j: make_move(row, col))
            b.place(x=x, y=y, width=100, height=100)
            buttons.append(b)


def main():
    root = tk.Tk()
    root.title("Tic Tac Toe")
    create_ui(root)
    root.mainloop()


if __name__ == "__main__":
    main()
