import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 屏幕设置
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("计算小能手")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
LIGHT_GRAY = (200, 200, 200)

# 修复中文显示：使用系统中文字体
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_large = get_chinese_font(64)
font_medium = get_chinese_font(48)
font_small = get_chinese_font(32)

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

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)
        pygame.draw.rect(screen, BLACK, self.rect, 2)
        text_surface = font_small.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 is_clicked(self, pos):
        return self.rect.collidepoint(pos)

# 生成题目
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, 50)
        b = random.randint(1, 50)
        op = random.choice(['+', '-', '*'])
    else:
        a = random.randint(1, 100)
        b = random.randint(1, 100)
        op = random.choice(['+', '-', '*', '/'])
        if op == '/':
            b = random.randint(1, 10)
            a = b * random.randint(1, 10)
    
    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():
    current_problem, current_answer = generate_problem()
    user_answer = ""
    score = 0
    total = 0
    feedback = ""
    feedback_color = BLACK
    
    # 难度按钮
    easy_button = Button(50, 320, 100, 50, "简单")
    medium_button = Button(200, 320, 100, 50, "中等")
    hard_button = Button(350, 320, 100, 50, "困难")
    difficulty = "easy"
    
    while True:
        screen.fill(WHITE)
        
        # 绘制标题
        title = font_large.render("计算小能手", True, BLACK)
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))
        
        # 绘制分数
        score_text = font_medium.render(f"得分: {score}/{total}", True, BLACK)
        screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, 90))
        
        # 绘制题目
        problem_text = font_large.render(current_problem, True, BLACK)
        screen.blit(problem_text, (WIDTH//2 - problem_text.get_width()//2, 150))
        
        # 绘制用户答案
        answer_text = font_large.render(user_answer, True, BLACK)
        screen.blit(answer_text, (WIDTH//2 - answer_text.get_width()//2, 220))
        
        # 绘制反馈
        feedback_text = font_medium.render(feedback, True, feedback_color)
        screen.blit(feedback_text, (WIDTH//2 - feedback_text.get_width()//2, 280))
        
        # 绘制难度按钮
        easy_button.draw(screen)
        medium_button.draw(screen)
        hard_button.draw(screen)
        
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if easy_button.is_clicked(pos):
                    difficulty = "easy"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    feedback = ""
                elif medium_button.is_clicked(pos):
                    difficulty = "medium"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    feedback = ""
                elif hard_button.is_clicked(pos):
                    difficulty = "hard"
                    current_problem, current_answer = generate_problem(difficulty)
                    user_answer = ""
                    feedback = ""
            
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                elif event.key == pygame.K_RETURN:
                    if user_answer:
                        total += 1
                        if int(user_answer) == current_answer:
                            score += 1
                            feedback = "正确！太棒了！"
                            feedback_color = GREEN
                        else:
                            feedback = f"错误，正确答案是 {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() or (event.unicode == '-' and not user_answer):
                    user_answer += event.unicode
        
        pygame.display.flip()

if __name__ == "__main__":
    main()