import random
import tkinter as tk
from anytree import Node, RenderTree

class Game:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("24点游戏")
        self.root.geometry("400x300")
        self.root.resizable(False, False)

        self.numbers = [random.randint(1, 9) for _ in range(4)]
        self.expression = tk.StringVar()
        self.expression.set("输入表达式")

        self.number_labels = []
        for i in range(4):
            label = tk.Label(self.root, text=str(self.numbers[i]), font=("Arial", 24))
            label.place(x=50 + i * 80, y=50)
            self.number_labels.append(label)

        input_entry = tk.Entry(self.root, textvariable=self.expression, font=("Arial", 24))
        input_entry.place(x=50, y=150)

        calculate_button = tk.Button(self.root, text="计算", font=("Arial", 24), command=self.calculate)
        calculate_button.place(x=250, y=150)

        self.result_label = tk.Label(self.root, text="", font=("Arial", 24))
        self.result_label.place(x=50, y=200)

    def calculate(self):
        try:
            root_node = Node("root")
            expression = self.expression.get()
            for char in expression:
                if char.isdigit():
                    node = Node(char, parent=root_node)
                elif char == "+":
                    node = Node(char, parent=root_node)
                elif char == "-":
                    node = Node(char, parent=root_node)
                elif char == "*":
                    node = Node(char, parent=root_node)
                elif char == "/":
                    node = Node(char, parent=root_node)
                else:
                    raise Exception("Invalid character")

            result = eval(expression)
            if result == 24:
                self.result_label.config(text="正确")
            else:
                self.result_label.config(text="错误")

            for pre, fill, node in RenderTree(root_node):
                print("%s%s" % (pre, node.name))

        except Exception as e:
            print(e)
            self.result_label.config(text="错误")

game = Game()
game.root.mainloop()
