import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 700, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("限时口算训练器")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
LIGHT_GRAY = (220, 220, 220)
GREEN = (34, 139, 34)
RED = (220, 20, 60)
BLUE = (70, 130, 180)
YELLOW = (255, 215, 0)

# 修复中文显示：使用系统中文字体
def get_chinese_font(size):
    font_names = [
        "SimHei", "Microsoft YaHei", "SimSun",
        "PingFang SC", "Heiti SC",
        "WenQuanYi Micro Hei", "Noto Sans CJK SC"
    ]
    
    for font_name in font_names:
        try:
            font = pygame.font.SysFont(font_name, size)
            test_text = font.render("测试", True, BLACK)
            if test_text.get_width() > 10:
                return font
        except:
            continue
    
    print("警告：未找到支持中文的字体，中文可能显示为方块")
    return pygame.font.Font(None, size)

# 字体设置
font_title = get_chinese_font(48)
font_large = get_chinese_font(40)
font_medium = get_chinese_font(28)
font_small = get_chinese_font(22)

# 按钮类
class Button:
    def __init__(self, x, y, w, h, text, color=LIGHT_GRAY, hover_color=GRAY):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text
        self.color = color
        self.hover_color = hover_color
        self.is_hovered = False

    def draw(self, screen):
        current_color = self.hover_color if self.is_hovered else self.color
        pygame.draw.rect(screen, current_color, self.rect, border_radius=8)
        pygame.draw.rect(screen, BLACK, self.rect, 2, border_radius=8)
        text_surface = font_medium.render(self.text, True, BLACK)
        screen.blit(text_surface, (self.rect.x + self.rect.width//2 - text_surface.get_width()//2,
                                  self.rect.y + self.rect.height//2 - text_surface.get_height()//2))

    def handle_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.is_hovered = self.rect.collidepoint(event.pos)
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.rect.collidepoint(event.pos):
                return True
        return False

# 生成题目
def generate_problem(difficulty="easy"):
    if difficulty == "easy":
        a = random.randint(1, 20)
        b = random.randint(1, 20)
        op = random.choice(['+', '-'])
        if op == '-' and a < b:
            a, b = b, a
    elif difficulty == "medium":
        a = random.randint(1, 100)
        b = random.randint(1, 100)
        op = random.choice(['+', '-', '×'])
        if op == '-' and a < b:
            a, b = b, a
        if op == '×':
            a = random.randint(1, 12)
            b = random.randint(1, 12)
    else:
        a = random.randint(1, 100)
        b = random.randint(1, 100)
        op = random.choice(['+', '-', '×', '÷'])
        if op == '-' and a < b:
            a, b = b, a
        if op == '×':
            a = random.randint(2, 20)
            b = random.randint(2, 20)
        if op == '÷':
            b = random.randint(2, 12)
            a = b * random.randint(2, 15)
    
    if op == '+':
        answer = a + b
    elif op == '-':
        answer = a - b
    elif op == '×':
        answer = a * b
    else:
        answer = a // b
    
    return f"{a} {op} {b} = ?", answer

# 主程序
def main():
    # 游戏状态: menu-菜单, playing-游戏中, result-结算
    state = "menu"
    difficulty = "easy"
    difficulty_name = "简单"
    GAME_TIME = 60  # 游戏时长60秒
    
    # 游戏数据
    current_problem = ""
    current_answer = 0
    user_answer = ""
    score = 0
    total = 0
    start_time = 0
    feedback = ""
    feedback_color = BLACK
    
    # 按钮
    easy_btn = Button(150, 200, 120, 60, "简单模式")
    medium_btn = Button(290, 200, 120, 60, "中等模式")
    hard_btn = Button(430, 200, 120, 60, "困难模式")
    restart_btn = Button(200, 380, 140, 50, "再来一局")
    menu_btn = Button(380, 380, 140, 50, "返回菜单")
    
    clock = pygame.time.Clock()
    
    while True:
        screen.fill(WHITE)
        
        # ========== 菜单界面 ==========
        if state == "menu":
            title = font_title.render("限时口算训练器", True, BLUE)
            screen.blit(title, (WIDTH//2 - title.get_width()//2, 60))
            
            tip = font_medium.render("请选择难度开始挑战（限时60秒）", True, BLACK)
            screen.blit(tip, (WIDTH//2 - tip.get_width()//2, 130))
            
            easy_btn.draw(screen)
            medium_btn.draw(screen)
            hard_btn.draw(screen)
            
            desc1 = font_small.render("简单：20以内加减法", True, GRAY)
            desc2 = font_small.render("中等：100以内加减 + 乘法表", True, GRAY)
            desc3 = font_small.render("困难：四则混合运算", True, GRAY)
            screen.blit(desc1, (150, 280))
            screen.blit(desc2, (290, 280))
            screen.blit(desc3, (430, 280))
            
            hint = font_small.render("按ESC退出 | 数字键输入答案 | 回车提交", True, GRAY)
            screen.blit(hint, (WIDTH//2 - hint.get_width()//2, 420))
        
        # ========== 游戏界面 ==========
        elif state == "playing":
            # 计算剩余时间
            elapsed = (pygame.time.get_ticks() - start_time) // 1000
            remaining = max(0, GAME_TIME - elapsed)
            
            # 时间到，进入结算
            if remaining <= 0:
                state = "result"
            
            # 顶部信息栏
            time_text = font_large.render("剩余时间: " + str(remaining) + "秒", True, RED if remaining <= 10 else BLACK)
            score_text = font_large.render("得分: " + str(score), True, GREEN)
            screen.blit(time_text, (50, 30))
            screen.blit(score_text, (500, 30))
            
            # 难度显示
            diff_text = font_medium.render("难度: " + difficulty_name, True, BLUE)
            screen.blit(diff_text, (WIDTH//2 - diff_text.get_width()//2, 40))
            
            # 题目
            problem_text = font_title.render(current_problem, True, BLACK)
            screen.blit(problem_text, (WIDTH//2 - problem_text.get_width()//2, 140))
            
            # 答案输入框
            input_rect = pygame.Rect(200, 230, 300, 70)
            pygame.draw.rect(screen, LIGHT_GRAY, input_rect, border_radius=8)
            pygame.draw.rect(screen, BLACK, input_rect, 2, border_radius=8)
            
            display_text = user_answer if user_answer else " "
            answer_text = font_title.render(display_text, True, BLACK)
            screen.blit(answer_text, (input_rect.centerx - answer_text.get_width()//2,
                                     input_rect.centery - answer_text.get_height()//2))
            
            # 反馈信息
            if feedback:
                fb_text = font_medium.render(feedback, True, feedback_color)
                screen.blit(fb_text, (WIDTH//2 - fb_text.get_width()//2, 330))
            
            # 统计
            total_text = font_medium.render("已答题数: " + str(total), True, BLACK)
            screen.blit(total_text, (WIDTH//2 - total_text.get_width()//2, 390))
            
            # 进度条
            bar_width = 600
            bar_x = 50
            bar_y = 450
            ratio = remaining / GAME_TIME
            pygame.draw.rect(screen, LIGHT_GRAY, (bar_x, bar_y, bar_width, 20))
            bar_color = GREEN if ratio > 0.3 else RED
            pygame.draw.rect(screen, bar_color, (bar_x, bar_y, bar_width * ratio, 20))
            pygame.draw.rect(screen, BLACK, (bar_x, bar_y, bar_width, 20), 2)
        
        # ========== 结算界面 ==========
        elif state == "result":
            title = font_title.render("时间到！", True, RED)
            screen.blit(title, (WIDTH//2 - title.get_width()//2, 60))
            
            # 结算数据
            if total > 0:
                accuracy = score / total * 100
            else:
                accuracy = 0
            
            lines = [
                "总题数: " + str(total) + " 道",
                "答对: " + str(score) + " 道",
                "正确率: " + "{:.1f}".format(accuracy) + "%",
                "用时: " + str(GAME_TIME) + " 秒"
            ]
            
            for i, line in enumerate(lines):
                text = font_large.render(line, True, BLACK)
                screen.blit(text, (WIDTH//2 - text.get_width()//2, 150 + i * 60))
            
            restart_btn.draw(screen)
            menu_btn.draw(screen)
        
        # ========== 事件处理 ==========
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                
                # 游戏中输入答案
                if state == "playing":
                    if event.key == pygame.K_RETURN:
                        if user_answer:
                            total += 1
                            if int(user_answer) == current_answer:
                                score += 1
                                feedback = "正确！"
                                feedback_color = GREEN
                            else:
                                feedback = "错误，正确答案: " + str(current_answer)
                                feedback_color = RED
                            # 生成新题
                            current_problem, current_answer = generate_problem(difficulty)
                            user_answer = ""
                    elif event.key == pygame.K_BACKSPACE:
                        user_answer = user_answer[:-1]
                    elif event.unicode.isdigit():
                        user_answer += event.unicode
            
            # 菜单按钮
            if state == "menu":
                if easy_btn.handle_event(event):
                    difficulty = "easy"
                    difficulty_name = "简单"
                    state = "playing"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    score = 0
                    total = 0
                    feedback = ""
                    start_time = pygame.time.get_ticks()
                
                if medium_btn.handle_event(event):
                    difficulty = "medium"
                    difficulty_name = "中等"
                    state = "playing"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    score = 0
                    total = 0
                    feedback = ""
                    start_time = pygame.time.get_ticks()
                
                if hard_btn.handle_event(event):
                    difficulty = "hard"
                    difficulty_name = "困难"
                    state = "playing"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    score = 0
                    total = 0
                    feedback = ""
                    start_time = pygame.time.get_ticks()
            
            # 结算按钮
            if state == "result":
                if restart_btn.handle_event(event):
                    state = "playing"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    score = 0
                    total = 0
                    feedback = ""
                    start_time = pygame.time.get_ticks()
                
                if menu_btn.handle_event(event):
                    state = "menu"
        
        pygame.display.flip()
        clock.tick(60)

if __name__ == "__main__":
    main()