# math_practice.py
import tkinter as tk
from tkinter import messagebox
import random

class MathPracticeApp:
    def __init__(self, root):
        self.root = root
        self.root.title("数学计算小能手练习器")
        self.root.geometry("540x440")
        self.root.resizable(False, False)

        # 全局参数
        self.mode = "add_sub"    # add_sub加减 / mul九九乘法 / four四则混合
        self.right_cnt = 0
        self.total_cnt = 0
        self.num1 = 0
        self.num2 = 0
        self.op = ""
        self.std_ans = 0

        # 顶部模式切换按钮区
        top_frame = tk.Frame(root)
        top_frame.pack(pady=12)
        tk.Button(top_frame, text="加减练习", width=9, command=lambda: self.switch_mode("add_sub")).grid(row=0, column=0, padx=6)
        tk.Button(top_frame, text="九九乘法", width=9, command=lambda: self.switch_mode("mul")).grid(row=0, column=1, padx=6)
        tk.Button(top_frame, text="四则混合", width=9, command=lambda: self.switch_mode("four")).grid(row=0, column=2, padx=6)
        tk.Button(top_frame, text="清空统计", width=9, command=self.reset_data).grid(row=0, column=3, padx=6)

        # 题目展示区域
        self.q_text = tk.StringVar(value="点击按钮开始做题")
        question_label = tk.Label(root, textvariable=self.q_text, font=("黑体", 32), fg="#111111")
        question_label.pack(pady=40)

        # 答案输入框
        input_frame = tk.Frame(root)
        input_frame.pack()
        tk.Label(input_frame, text="你的答案：", font=("宋体", 15)).grid(row=0, column=0)
        self.ans_entry = tk.Entry(input_frame, font=("宋体", 20), width=12, justify="center")
        self.ans_entry.grid(row=0, column=1, padx=12)
        # 按下回车键自动提交
        self.ans_entry.bind("<Return>", self.judge_answer)

        # 功能按钮
        btn_frame = tk.Frame(root)
        btn_frame.pack(pady=25)
        tk.Button(btn_frame, text="提交答案", command=self.judge_answer, font=("宋体", 13), width=11).grid(row=0, column=0, padx=10)
        tk.Button(btn_frame, text="下一题", command=self.create_question, font=("宋体", 13), width=11).grid(row=0, column=1, padx=10)

        # 数据统计栏
        self.stat_text = tk.StringVar(value="正确率：0.0% | 答对：0题 | 总答题：0题")
        stat_label = tk.Label(root, textvariable=self.stat_text, font=("宋体", 12), fg="#333333")
        stat_label.pack(pady=8)

        # 初始化第一道题目
        self.create_question()

    # 切换练习模式
    def switch_mode(self, new_mode):
        self.mode = new_mode
        self.reset_data()
        self.create_question()

    # 清空答题统计数据
    def reset_data(self):
        self.right_cnt = 0
        self.total_cnt = 0
        self.update_stat_info()

    # 更新下方统计文字
    def update_stat_info(self):
        if self.total_cnt == 0:
            rate = 0.0
        else:
            rate = self.right_cnt / self.total_cnt * 100
        self.stat_text.set(f"正确率：{rate:.1f}% | 答对：{self.right_cnt}题 | 总答题：{self.total_cnt}题")

    # 自动生成对应模式的数学题
    def create_question(self):
        self.ans_entry.delete(0, tk.END)
        if self.mode == "add_sub":
            # 两位数加减法
            self.num1 = random.randint(1, 99)
            self.num2 = random.randint(1, 99)
            self.op = random.choice(["+", "-"])
            if self.op == "+":
                self.std_ans = self.num1 + self.num2
            else:
                # 保证减法结果≥0
                if self.num1 < self.num2:
                    self.num1, self.num2 = self.num2, self.num1
                self.std_ans = self.num1 - self.num2

        elif self.mode == "mul":
            # 九九乘法表 1~9
            self.num1 = random.randint(1, 9)
            self.num2 = random.randint(1, 9)
            self.op = "×"
            self.std_ans = self.num1 * self.num2

        elif self.mode == "four":
            # 四则混合运算
            self.num1 = random.randint(2, 35)
            self.num2 = random.randint(2, 12)
            self.op = random.choice(["+", "-", "×", "÷"])
            if self.op == "+":
                self.std_ans = self.num1 + self.num2
            elif self.op == "-":
                if self.num1 < self.num2:
                    self.num1, self.num2 = self.num2, self.num1
                self.std_ans = self.num1 - self.num2
            elif self.op == "×":
                self.std_ans = self.num1 * self.num2
            else:
                # 除法强制整除，不会出现小数
                self.num1 = self.num2 * random.randint(1, 10)
                self.std_ans = self.num1 // self.num2

        self.q_text.set(f"{self.num1} {self.op} {self.num2} = ?")

    # 判断答案对错
    def judge_answer(self, event=None):
        input_str = self.ans_entry.get().strip()
        # 校验输入必须是数字
        if not input_str.isdigit():
            messagebox.showwarning("输入错误", "请输入纯数字答案！")
            return

        user_ans = int(input_str)
        self.total_cnt += 1

        if user_ans == self.std_ans:
            self.right_cnt += 1
            messagebox.showinfo("回答正确", "太棒啦，恭喜答对！")
        else:
            messagebox.showerror("回答错误", f"很遗憾答错啦\n正确答案：{self.std_ans}")

        self.update_stat_info()
        self.create_question()

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