import random
import tkinter as tk
from tkinter import messagebox

class MathPracticeApp:
    def __init__(self, root):
        self.root = root
        self.root.title("🧮 计算小能手练习器")
        self.root.geometry("520x380")
        self.root.resizable(False, False)

        # 答题数据
        self.mode = None       # mul乘法 / four四则
        self.max_num = 30      # 四则最大数值
        self.question_count = 0
        self.correct = 0
        self.current_a = 0
        self.current_b = 0
        self.current_op = ""
        self.answer = 0

        # 界面组件
        self.create_widgets()

    def create_widgets(self):
        # 标题
        title_label = tk.Label(self.root, text="计算小能手", font=("黑体", 24, "bold"))
        title_label.pack(pady=10)

        # 题目显示
        self.q_label = tk.Label(self.root, text="请选择练习模式开始答题", font=("黑体", 22))
        self.q_label.pack(pady=15)

        # 答案输入框
        input_frame = tk.Frame(self.root)
        input_frame.pack()
        tk.Label(input_frame, text="你的答案：", font=("黑体", 14)).grid(row=0, column=0)
        self.ans_entry = tk.Entry(input_frame, font=("黑体", 16), width=10)
        self.ans_entry.grid(row=0, column=1, padx=10)
        self.ans_entry.bind("<Return>", self.check_answer)  # 回车提交

        # 提交按钮
        submit_btn = tk.Button(self.root, text="提交答案", command=self.check_answer,
                               font=("黑体", 13), bg="#66cc66", width=12)
        submit_btn.pack(pady=12)

        # 信息栏（分数）
        self.info_label = tk.Label(self.root, text="题目：0 | 正确：0", font=("黑体", 12))
        self.info_label.pack()

        # 功能按钮区域
        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=25)

        tk.Button(btn_frame, text="九九乘法练习", command=self.start_mul,
                  font=("黑体", 12), width=12).grid(row=0, column=0, padx=8)
        tk.Button(btn_frame, text="四则运算练习", command=self.start_four,
                  font=("黑体", 12), width=12).grid(row=0, column=1, padx=8)
        tk.Button(btn_frame, text="重置成绩", command=self.reset_score,
                  font=("黑体", 12), width=12).grid(row=1, column=0, padx=8, pady=6)
        tk.Button(btn_frame, text="退出程序", command=self.root.quit,
                  font=("黑体", 12), width=12).grid(row=1, column=1, padx=8, pady=6)

    def reset_score(self):
        """清空分数"""
        self.question_count = 0
        self.correct = 0
        self.mode = None
        self.q_label.config(text="请选择练习模式开始答题")
        self.update_info()
        self.ans_entry.delete(0, tk.END)

    def update_info(self):
        self.info_label.config(text=f"题目：{self.question_count} | 正确：{self.correct}")

    def start_mul(self):
        """启动乘法练习"""
        self.mode = "mul"
        self.next_question()

    def start_four(self):
        """启动四则运算"""
        self.mode = "four"
        self.next_question()

    def next_question(self):
        """生成下一题"""
        self.ans_entry.delete(0, tk.END)
        if self.mode == "mul":
            # 乘法口诀
            self.current_a = random.randint(1, 9)
            self.current_b = random.randint(1, 9)
            self.current_op = "×"
            self.answer = self.current_a * self.current_b
        else:
            # 四则运算
            ops = ["+", "-", "×", "÷"]
            self.current_op = random.choice(ops)
            if self.current_op == "÷":
                b = random.randint(1, self.max_num)
                self.answer = random.randint(1, self.max_num)
                self.current_a = self.answer * b
                self.current_b = b
            elif self.current_op == "-":
                self.current_a = random.randint(1, self.max_num)
                self.current_b = random.randint(1, self.current_a)
                self.answer = self.current_a - self.current_b
            elif self.current_op == "+":
                self.current_a = random.randint(1, self.max_num)
                self.current_b = random.randint(1, self.max_num)
                self.answer = self.current_a + self.current_b
            else:
                self.current_a = random.randint(1, self.max_num)
                self.current_b = random.randint(1, self.max_num)
                self.answer = self.current_a * self.current_b

        self.q_label.config(text=f"{self.current_a} {self.current_op} {self.current_b} = ?")

    def check_answer(self, event=None):
        """核对答案"""
        if self.mode is None:
            messagebox.showwarning("提示", "请先选择练习模式！")
            return
        content = self.ans_entry.get().strip()
        if not content.isdigit():
            messagebox.showerror("输入错误", "请输入整数数字！")
            return

        user_ans = int(content)
        self.question_count += 1
        if user_ans == self.answer:
            self.correct += 1
            messagebox.showinfo("✅ 回答正确！", "太棒啦！")
        else:
            messagebox.showerror("❌ 答错了", f"正确答案是：{self.answer}")

        self.update_info()
        self.next_question()


if __name__ == "__main__":
    window = tk.Tk()
    app = MathPracticeApp(window)
    window.mainloop()
