import pygame
import random
import sys

# ======================
# 初始化
# ======================
pygame.init()
WIDTH, HEIGHT = 800, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("数学题练习器")

font_big = pygame.font.SysFont("simhei", 48)
font_mid = pygame.font.SysFont("simhei", 36)
font_small = pygame.font.SysFont("simhei", 24)
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLUE = (0, 100, 200)

MODE_SELECT = 0
MODE_ARITHMETIC = 1
MODE_MULTIPLY = 2

mode = MODE_SELECT
score = 0
total = 0
question = ""
answer = ""
correct_answer = None
feedback = ""
feedback_timer = 0


# ======================
# 生成题目
# ======================
def generate_arithmetic():
    ops = ['+', '-', '*', '/']
    op = random.choice(ops)
    if op == '+':
        a = random.randint(1, 50)
        b = random.randint(1, 50)
        ans = a + b
    elif op == '-':
        a = random.randint(1, 50)
        b = random.randint(1, a)
        ans = a - b
    elif op == '*':
        a = random.randint(1, 12)
        b = random.randint(1, 12)
        ans = a * b
    else:  # division
        b = random.randint(1, 12)
        ans = random.randint(1, 12)
        a = b * ans
    return f"{a} {op} {b} = ?", ans


def generate_multiplication():
    a = random.randint(1, 9)
    b = random.randint(1, 9)
    return f"{a} × {b} = ?", a * b


# ======================
# 绘制文字
# ======================
def draw_text(text, font, color, x, y):
    img = font.render(text, True, color)
    screen.blit(img, (x, y))


# ======================
# 主循环
# ======================
running = True
while running:
    screen.fill(WHITE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if mode == MODE_SELECT:
                if event.key == pygame.K_1:
                    mode = MODE_ARITHMETIC
                    question, correct_answer = generate_arithmetic()
                    answer = ""
                    feedback = ""
                elif event.key == pygame.K_2:
                    mode = MODE_MULTIPLY
                    question, correct_answer = generate_multiplication()
                    answer = ""
                    feedback = ""

            elif mode in (MODE_ARITHMETIC, MODE_MULTIPLY):
                if event.key == pygame.K_RETURN and answer != "":
                    total += 1
                    if int(answer) == correct_answer:
                        score += 1
                        feedback = "✔ 正确！"
                    else:
                        feedback = f"✘ 错误，正确答案是 {correct_answer}"
                    feedback_timer = 90

                    if mode == MODE_ARITHMETIC:
                        question, correct_answer = generate_arithmetic()
                    else:
                        question, correct_answer = generate_multiplication()
                    answer = ""

                elif event.key == pygame.K_BACKSPACE:
                    answer = answer[:-1]

                elif event.key == pygame.K_r:
                    score = 0
                    total = 0
                    answer = ""
                    feedback = ""
                    if mode == MODE_ARITHMETIC:
                        question, correct_answer = generate_arithmetic()
                    else:
                        question, correct_answer = generate_multiplication()

                elif event.unicode.isdigit():
                    answer += event.unicode

                elif event.key == pygame.K_ESCAPE:
                    mode = MODE_SELECT

    # ======================
    # 界面绘制
    # ======================
    if mode == MODE_SELECT:
        draw_text("数学题练习器", font_big, BLUE, 240, 80)
        draw_text("按 1 → 四则运算练习", font_mid, BLACK, 220, 180)
        draw_text("按 2 → 乘法表练习", font_mid, BLACK, 240, 240)
        draw_text("ESC 返回此界面", font_small, BLACK, 300, 320)

    else:
        draw_text(question, font_big, BLACK, 260, 80)
        draw_text(f"你的答案：{answer}", font_mid, BLUE, 260, 160)
        draw_text(f"得分：{score} / {total}", font_mid, GREEN, 260, 230)

        if feedback_timer > 0:
            color = GREEN if "正确" in feedback else RED
            draw_text(feedback, font_mid, color, 260, 300)
            feedback_timer -= 1

        draw_text("Enter 提交 | Backspace 删除 | R 重开 | ESC 返回",
                  font_small, BLACK, 120, 420)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()