import pygame
import random
import sys
import time

pygame.init()

WIDTH, HEIGHT = 700, 420
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("数学题练习器 · AI 对手挑战")

# ✅ 关键修复：使用系统绝对路径中文字体
FONT = pygame.font.Font("C:/Windows/Fonts/simhei.ttf", 26)
BIG_FONT = pygame.font.Font("C:/Windows/Fonts/simhei.ttf", 40)

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 180, 0)
RED = (200, 0, 0)
BLUE = (70, 130, 180)
GRAY = (230, 230, 230)

clock = pygame.time.Clock()

state = "menu"
mode = "add"

player_score = 0
ai_score = 0
total = 0

question = ""
answer = 0
user_text = ""

TIME_LIMIT = 60
start_ticks = 0

AI_REACTION_MIN = 1.0
AI_REACTION_MAX = 2.0
AI_ACCURACY = 0.85

ai_thinking = False
ai_think_start = 0
ai_answer_time = 0
ai_answered = False


def make_question():
    global question, answer, ai_thinking, ai_answered
    a = random.randint(1, 20)
    b = random.randint(1, 20)

    if mode == "add":
        question, answer = f"{a} + {b} = ?", a + b
    elif mode == "sub":
        a, b = max(a, b), min(a, b)
        question, answer = f"{a} - {b} = ?", a - b
    elif mode == "mul":
        a, b = random.randint(1, 9), random.randint(1, 9)
        question, answer = f"{a} × {b} = ?", a * b

    ai_thinking = True
    ai_answered = False


def draw_text(text, x, y, font=FONT, color=BLACK):
    img = font.render(text, True, color)
    screen.blit(img, (x, y))


def menu():
    screen.fill(WHITE)
    draw_text("🧠 数学题 · AI 对手挑战", 180, 40, BIG_FONT, BLUE)
    draw_text("1 - 加法对战", 260, 120)
    draw_text("2 - 减法对战", 260, 160)
    draw_text("3 - 乘法对战", 260, 200)
    draw_text("难度：普通", 260, 240)
    draw_text("按数字键开始", 250, 320)


def quiz():
    global ai_thinking, ai_think_start, ai_answer_time
    global ai_answered, ai_score, player_score, total

    screen.fill(WHITE)

    seconds = (pygame.time.get_ticks() - start_ticks) // 1000
    remain = max(0, TIME_LIMIT - seconds)

    draw_text(f"你：{player_score}", 30, 20, FONT, GREEN)
    draw_text(f"AI：{ai_score}", 580, 20, FONT, RED)
    draw_text(f"题数：{total}", 300, 20)
    draw_text(f"⏱ 剩余：{remain} 秒", 260, 60, FONT, RED if remain <= 10 else BLACK)

    draw_text(question, 200, 130, BIG_FONT)

    pygame.draw.rect(screen, BLACK, (180, 200, 340, 50), 2)
    draw_text(user_text, 190, 215, FONT)

    draw_text("回车提交  ESC 返回", 250, 280)

    if ai_thinking and not ai_answered:
        if ai_think_start == 0:
            ai_think_start = time.time()
            ai_answer_time = ai_think_start + random.uniform(AI_REACTION_MIN, AI_REACTION_MAX)

        if time.time() >= ai_answer_time:
            total += 1
            if random.random() < AI_ACCURACY:
                ai_score += 1
            ai_answered = True
            ai_thinking = False
            ai_think_start = 0
            pygame.time.delay(500)
            make_question()

    if remain <= 0:
        pygame.time.delay(300)
        end_quiz()


def end_quiz():
    global state
    state = "result"


def result():
    screen.fill(GRAY)
    draw_text("⏰ 时间到！", 280, 50, BIG_FONT, BLUE)
    draw_text(f"你得分：{player_score}", 260, 140, FONT, GREEN)
    draw_text(f"AI 得分：{ai_score}", 260, 180, FONT, RED)
    draw_text("按任意键返回菜单", 240, 280)


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

        if state == "menu":
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    mode = "add"
                elif event.key == pygame.K_2:
                    mode = "sub"
                elif event.key == pygame.K_3:
                    mode = "mul"
                else:
                    continue

                player_score, ai_score, total = 0, 0, 0
                make_question()
                start_ticks = pygame.time.get_ticks()
                state = "quiz"

        elif state == "quiz":
            seconds = (pygame.time.get_ticks() - start_ticks) // 1000
            if seconds >= TIME_LIMIT:
                continue

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    state = "menu"

                elif event.key == pygame.K_RETURN:
                    if user_text.lstrip("-").isdigit():
                        total += 1
                        if int(user_text) == answer:
                            player_score += 1
                        make_question()
                        user_text = ""
                    else:
                        user_text = ""

                elif event.key == pygame.K_BACKSPACE:
                    user_text = user_text[:-1]
                else:
                    if event.unicode.isdigit() or event.unicode == "-":
                        user_text += event.unicode

        elif state == "result":
            if event.type == pygame.KEYDOWN:
                state = "menu"

    if state == "menu":
        menu()
    elif state == "quiz":
        quiz()
    elif state == "result":
        result()

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

pygame.quit()
sys.exit()