import pygame
import sys
import math

# 初始化 Pygame
pygame.init()

# 定义颜色
LIGHT_THEME = {
    "bg": (245, 245, 245),
    "display_bg": (255, 255, 255),
    "button_bg": (240, 240, 240),
    "button_hover": (220, 220, 220),
    "text": (30, 30, 30),
    "operator": (0, 120, 215),
    "function": (0, 150, 100),
    "equals": (200, 80, 60),
    "clear": (220, 80, 60),
    "border": (200, 200, 200)
}

DARK_THEME = {
    "bg": (30, 30, 35),
    "display_bg": (40, 40, 45),
    "button_bg": (50, 50, 55),
    "button_hover": (70, 70, 75),
    "text": (240, 240, 240),
    "operator": (0, 150, 255),
    "function": (0, 180, 130),
    "equals": (255, 100, 80),
    "clear": (255, 100, 80),
    "border": (60, 60, 65)
}

BLUE_THEME = {
    "bg": (20, 30, 50),
    "display_bg": (30, 40, 60),
    "button_bg": (40, 50, 70),
    "button_hover": (60, 70, 90),
    "text": (240, 240, 250),
    "operator": (0, 180, 255),
    "function": (100, 200, 150),
    "equals": (255, 120, 100),
    "clear": (255, 120, 100),
    "border": (50, 60, 80)
}

# 当前主题
current_theme = "light"
themes = {
    "light": LIGHT_THEME,
    "dark": DARK_THEME,
    "blue": BLUE_THEME
}
colors = themes[current_theme]

# 设置窗口尺寸
WIDTH, HEIGHT = 600, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("高级科学计算器")

# 字体初始化 - 使用更可靠的方式
def init_fonts():
    """初始化字体"""
    fonts = {}
    
    # 尝试加载不同大小的字体
    sizes = {
        'large': 42,
        'medium': 32,
        'small': 24,
        'tiny': 18
    }
    
    # 尝试不同的字体名称
    font_names = ['arial', 'simsun', 'fangsong', 'microsoftyahei', 'helvetica', None]
    
    for name, size in sizes.items():
        font_loaded = False
        for font_name in font_names:
            try:
                if font_name:
                    fonts[name] = pygame.font.SysFont(font_name, size)
                else:
                    fonts[name] = pygame.font.Font(None, size)
                font_loaded = True
                break
            except:
                continue
        
        # 如果所有字体都失败，使用默认字体
        if not font_loaded:
            fonts[name] = pygame.font.Font(None, size)
    
    return fonts

# 初始化字体
fonts = init_fonts()
font_large = fonts['large']
font_medium = fonts['medium']
font_small = fonts['small']
font_tiny = fonts['tiny']

# 计算器状态类
class CalculatorState:
    def __init__(self):
        self.current_input = "0"
        self.previous_input = ""
        self.operator = ""
        self.result = None
        self.memory = 0
        self.is_radians = True
        self.error_message = ""
        self.waiting_for_second = False

calc_state = CalculatorState()

# 按钮定义
class Button:
    def __init__(self, label, value, rect, color_type="number", tooltip=""):
        self.label = label
        self.value = value
        self.rect = rect
        self.color_type = color_type
        self.tooltip = tooltip

# 创建按钮
buttons = []

# 第一行：设置和内存按钮
buttons.append(Button("MC", "MC", pygame.Rect(10, 150, 70, 50), "memory", "清除内存"))
buttons.append(Button("MR", "MR", pygame.Rect(85, 150, 70, 50), "memory", "读取内存"))
buttons.append(Button("M+", "M+", pygame.Rect(160, 150, 70, 50), "memory", "加到内存"))
buttons.append(Button("M-", "M-", pygame.Rect(235, 150, 70, 50), "memory", "从内存减"))
buttons.append(Button("MS", "MS", pygame.Rect(310, 150, 70, 50), "memory", "存储到内存"))
buttons.append(Button("RAD", "RAD/DEG", pygame.Rect(385, 150, 100, 50), "setting", "切换弧度/角度"))
buttons.append(Button("π", "pi", pygame.Rect(490, 150, 100, 50), "function", "圆周率π"))

# 第二行：科学函数
buttons.append(Button("sin", "sin", pygame.Rect(10, 205, 70, 50), "function", "正弦函数"))
buttons.append(Button("cos", "cos", pygame.Rect(85, 205, 70, 50), "function", "余弦函数"))
buttons.append(Button("tan", "tan", pygame.Rect(160, 205, 70, 50), "function", "正切函数"))
buttons.append(Button("log", "log10", pygame.Rect(235, 205, 70, 50), "function", "以10为底的对数"))
buttons.append(Button("ln", "ln", pygame.Rect(310, 205, 70, 50), "function", "自然对数"))
buttons.append(Button("√", "sqrt", pygame.Rect(385, 205, 100, 50), "function", "平方根"))
buttons.append(Button("x²", "x^2", pygame.Rect(490, 205, 100, 50), "function", "平方"))

# 第三行：更多函数和清除
buttons.append(Button("asin", "asin", pygame.Rect(10, 260, 70, 50), "function", "反正弦"))
buttons.append(Button("acos", "acos", pygame.Rect(85, 260, 70, 50), "function", "反余弦"))
buttons.append(Button("atan", "atan", pygame.Rect(160, 260, 70, 50), "function", "反正切"))
buttons.append(Button("10^x", "10^x", pygame.Rect(235, 260, 70, 50), "function", "10的x次方"))
buttons.append(Button("e^x", "e^x", pygame.Rect(310, 260, 70, 50), "function", "e的x次方"))
buttons.append(Button("1/x", "1/x", pygame.Rect(385, 260, 100, 50), "function", "倒数"))
buttons.append(Button("C", "C", pygame.Rect(490, 260, 100, 50), "clear", "清除"))

# 第四行：基本运算
buttons.append(Button("(", "(", pygame.Rect(10, 315, 70, 60), "operator", "左括号"))
buttons.append(Button(")", ")", pygame.Rect(85, 315, 70, 60), "operator", "右括号"))
buttons.append(Button("⌫", "DEL", pygame.Rect(160, 315, 70, 60), "clear", "删除"))
buttons.append(Button("÷", "/", pygame.Rect(235, 315, 70, 60), "operator", "除法"))
buttons.append(Button("CE", "CE", pygame.Rect(310, 315, 70, 60), "clear", "清除当前输入"))
buttons.append(Button("±", "+/-", pygame.Rect(385, 315, 100, 60), "function", "正负切换"))
buttons.append(Button("%", "%", pygame.Rect(490, 315, 100, 60), "operator", "百分比"))

# 数字和基本运算按钮
number_positions = [
    (10, 380, 70, 60), (85, 380, 70, 60), (160, 380, 70, 60),
    (10, 445, 70, 60), (85, 445, 70, 60), (160, 445, 70, 60),
    (10, 510, 70, 60), (85, 510, 70, 60), (160, 510, 70, 60),
    (10, 575, 145, 60), (160, 575, 70, 60)
]

numbers = ["7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "."]

for i, (x, y, w, h) in enumerate(number_positions):
    color_type = "number" if numbers[i] != "." else "function"
    tooltip = f"数字 {numbers[i]}" if numbers[i] != "." else "小数点"
    buttons.append(Button(numbers[i], numbers[i], pygame.Rect(x, y, w, h), color_type, tooltip))

# 运算符按钮
operator_positions = [
    (235, 380, 70, 60),  # -
    (235, 445, 70, 60),  # +
    (235, 510, 70, 125)  # =
]

operators = ["-", "+", "="]
operator_types = ["operator", "operator", "equals"]

for i, (x, y, w, h) in enumerate(operator_positions):
    tooltip = f"运算符 {operators[i]}" if operators[i] != "=" else "计算"
    buttons.append(Button(operators[i], operators[i], pygame.Rect(x, y, w, h), operator_types[i], tooltip))

# 更多运算符
buttons.append(Button("×", "*", pygame.Rect(310, 380, 70, 60), "operator", "乘法"))
buttons.append(Button("x^y", "^", pygame.Rect(310, 445, 70, 60), "function", "幂运算"))
buttons.append(Button("mod", "mod", pygame.Rect(310, 510, 70, 60), "function", "取模"))

# 更多函数
buttons.append(Button("|x|", "abs", pygame.Rect(385, 380, 100, 60), "function", "绝对值"))
buttons.append(Button("x!", "factorial", pygame.Rect(385, 445, 100, 60), "function", "阶乘"))
buttons.append(Button("e", "e", pygame.Rect(385, 510, 100, 60), "function", "自然常数"))

# 主题切换按钮
theme_buttons = [
    ("L", "theme_light", 10, 10, "light", "浅色主题"),
    ("D", "theme_dark", 65, 10, "dark", "深色主题"),
    ("B", "theme_blue", 120, 10, "blue", "蓝色主题"),
]

def draw_display():
    """绘制计算器显示区域"""
    # 显示区域背景
    pygame.draw.rect(screen, colors["display_bg"], (10, 50, WIDTH - 20, 90), border_radius=10)
    pygame.draw.rect(screen, colors["border"], (10, 50, WIDTH - 20, 90), 2, border_radius=10)
    
    # 历史记录显示（简化版，只显示当前运算）
    history_text = f"{calc_state.previous_input} {calc_state.operator}"
    
    # 确保字体可用
    try:
        history_surface = font_small.render(history_text, True, colors["text"])
    except:
        # 如果字体渲染失败，使用默认字体
        temp_font = pygame.font.Font(None, 24)
        history_surface = temp_font.render(history_text, True, colors["text"])
    
    screen.blit(history_surface, (WIDTH - history_surface.get_width() - 20, 55))
    
    # 当前模式显示
    mode_text = "RAD" if calc_state.is_radians else "DEG"
    mode_color = colors["function"] if calc_state.is_radians else colors["operator"]
    
    try:
        mode_surface = font_tiny.render(mode_text, True, mode_color)
    except:
        temp_font = pygame.font.Font(None, 18)
        mode_surface = temp_font.render(mode_text, True, mode_color)
    
    screen.blit(mode_surface, (20, 55))
    
    # 内存指示器
    if calc_state.memory != 0:
        mem_text = f"M: {calc_state.memory:.2f}"
        
        try:
            mem_surface = font_tiny.render(mem_text, True, colors["function"])
        except:
            temp_font = pygame.font.Font(None, 18)
            mem_surface = temp_font.render(mem_text, True, colors["function"])
        
        screen.blit(mem_surface, (20, 80))
    
    # 当前输入显示
    display_text = calc_state.current_input
    if calc_state.error_message:
        display_text = calc_state.error_message
    
    # 选择合适的字体大小
    display_font = font_large
    max_width = WIDTH - 40
    
    # 检查文本宽度
    try:
        text_width = display_font.size(display_text)[0]
    except:
        # 如果字体失败，使用默认字体
        display_font = pygame.font.Font(None, 42)
        text_width = display_font.size(display_text)[0]
    
    if text_width > max_width:
        display_font = font_medium
        try:
            text_width = display_font.size(display_text)[0]
        except:
            display_font = pygame.font.Font(None, 32)
            text_width = display_font.size(display_text)[0]
        
        if text_width > max_width:
            display_font = font_small
            try:
                text_width = display_font.size(display_text)[0]
            except:
                display_font = pygame.font.Font(None, 24)
                text_width = display_font.size(display_text)[0]
            
            if text_width > max_width:
                # 截断文本
                while text_width > max_width and len(display_text) > 1:
                    display_text = display_text[1:]
                    text_width = display_font.size(display_text)[0]
    
    # 右对齐显示
    try:
        text_surface = display_font.render(display_text, True, colors["text"])
    except:
        temp_font = pygame.font.Font(None, display_font.get_height())
        text_surface = temp_font.render(display_text, True, colors["text"])
    
    text_x = WIDTH - text_surface.get_width() - 20
    text_y = 90 if display_font.get_height() > 30 else 95
    screen.blit(text_surface, (text_x, text_y))

def draw_buttons():
    """绘制所有按钮"""
    mouse_pos = pygame.mouse.get_pos()
    
    for button in buttons:
        rect = button.rect
        is_hovered = rect.collidepoint(mouse_pos)
        
        # 确定按钮颜色
        if button.color_type == "number":
            base_color = colors["button_bg"]
        elif button.color_type == "operator":
            base_color = colors["operator"]
        elif button.color_type == "function":
            base_color = colors["function"]
        elif button.color_type == "equals":
            base_color = colors["equals"]
        elif button.color_type == "clear":
            base_color = colors["clear"]
        elif button.color_type == "memory":
            base_color = colors["function"]
        elif button.color_type == "setting":
            base_color = colors["button_bg"]
        else:
            base_color = colors["button_bg"]
        
        # 悬停效果
        if is_hovered and button.color_type not in ["equals", "clear"]:
            button_color = tuple(min(c + 20, 255) for c in base_color)
        else:
            button_color = base_color
        
        # 绘制按钮
        pygame.draw.rect(screen, button_color, rect, border_radius=8)
        pygame.draw.rect(screen, colors["border"], rect, 2, border_radius=8)
        
        # 绘制按钮文字
        text_color = colors["text"] if button.color_type in ["number", "setting"] else (255, 255, 255)
        
        try:
            text_surface = font_medium.render(button.label, True, text_color)
        except:
            # 如果字体渲染失败，使用默认字体
            temp_font = pygame.font.Font(None, 32)
            text_surface = temp_font.render(button.label, True, text_color)
        
        text_rect = text_surface.get_rect(center=rect.center)
        screen.blit(text_surface, text_rect)
        
        # 绘制工具提示
        if is_hovered and button.tooltip:
            draw_tooltip(button.tooltip, mouse_pos)

def draw_tooltip(text, position):
    """绘制工具提示"""
    try:
        tooltip_font = font_tiny
        text_surface = tooltip_font.render(text, True, (255, 255, 255))
    except:
        tooltip_font = pygame.font.Font(None, 18)
        text_surface = tooltip_font.render(text, True, (255, 255, 255))
    
    text_rect = text_surface.get_rect()
    
    # 背景
    bg_rect = text_rect.inflate(10, 5)
    bg_rect.topleft = (position[0] + 10, position[1] + 10)
    
    # 确保工具提示在屏幕内
    if bg_rect.right > WIDTH:
        bg_rect.right = position[0] - 10
    if bg_rect.bottom > HEIGHT:
        bg_rect.bottom = position[1] - 10
    
    pygame.draw.rect(screen, (50, 50, 50), bg_rect, border_radius=4)
    pygame.draw.rect(screen, (100, 100, 100), bg_rect, 1, border_radius=4)
    
    screen.blit(text_surface, (bg_rect.x + 5, bg_rect.y + 3))

def draw_theme_buttons():
    """绘制主题切换按钮"""
    for label, value, x, y, theme_name, tooltip in theme_buttons:
        rect = pygame.Rect(x, y, 50, 30)
        is_active = current_theme == theme_name
        
        # 按钮颜色
        if is_active:
            button_color = colors["operator"]
        else:
            button_color = colors["button_bg"]
        
        pygame.draw.rect(screen, button_color, rect, border_radius=5)
        pygame.draw.rect(screen, colors["border"], rect, 1, border_radius=5)
        
        # 按钮文字
        try:
            text_surface = font_medium.render(label, True, colors["text"])
        except:
            temp_font = pygame.font.Font(None, 32)
            text_surface = temp_font.render(label, True, colors["text"])
        
        text_rect = text_surface.get_rect(center=rect.center)
        screen.blit(text_surface, text_rect)
        
        # 工具提示
        if rect.collidepoint(pygame.mouse.get_pos()):
            draw_tooltip(tooltip, rect.topleft)

def handle_button_click(value):
    """处理按钮点击事件"""
    global current_theme, colors
    
    # 主题切换
    if value.startswith("theme_"):
        current_theme = value.split("_")[1]
        colors = themes[current_theme]
        return
    
    # 清除错误信息
    if calc_state.error_message:
        calc_state.error_message = ""
    
    try:
        # 数字输入
        if value.isdigit():
            if calc_state.current_input == "0" or calc_state.waiting_for_second:
                calc_state.current_input = value
                calc_state.waiting_for_second = False
            else:
                calc_state.current_input += value
        
        # 小数点
        elif value == ".":
            if "." not in calc_state.current_input:
                calc_state.current_input += "."
        
        # 基本运算符
        elif value in ["+", "-", "*", "/", "^", "mod"]:
            if calc_state.previous_input and calc_state.operator and not calc_state.waiting_for_second:
                calculate_result()
            calc_state.operator = value
            calc_state.previous_input = calc_state.current_input
            calc_state.waiting_for_second = True
        
        # 等号
        elif value == "=":
            if calc_state.previous_input and calc_state.operator:
                calculate_result()
        
        # 清除
        elif value == "C":
            calc_state.current_input = "0"
            calc_state.previous_input = ""
            calc_state.operator = ""
            calc_state.result = None
            calc_state.waiting_for_second = False
        
        # 清除当前输入
        elif value == "CE":
            calc_state.current_input = "0"
            calc_state.waiting_for_second = False
        
        # 删除
        elif value == "DEL":
            if len(calc_state.current_input) > 1:
                calc_state.current_input = calc_state.current_input[:-1]
            else:
                calc_state.current_input = "0"
        
        # 正负切换
        elif value == "+/-":
            if calc_state.current_input.startswith("-"):
                calc_state.current_input = calc_state.current_input[1:]
            else:
                calc_state.current_input = "-" + calc_state.current_input
        
        # 百分比
        elif value == "%":
            try:
                num = float(calc_state.current_input) / 100
                calc_state.current_input = format_number(num)
            except:
                calc_state.error_message = "错误"
        
        # 平方根
        elif value == "sqrt":
            try:
                num = float(calc_state.current_input)
                if num < 0:
                    calc_state.error_message = "无效输入"
                else:
                    result = math.sqrt(num)
                    calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 平方
        elif value == "x^2":
            try:
                num = float(calc_state.current_input)
                result = num ** 2
                calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 倒数
        elif value == "1/x":
            try:
                num = float(calc_state.current_input)
                if num == 0:
                    calc_state.error_message = "除零错误"
                else:
                    result = 1 / num
                    calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 绝对值
        elif value == "abs":
            try:
                num = float(calc_state.current_input)
                result = abs(num)
                calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 三角函数
        elif value in ["sin", "cos", "tan", "asin", "acos", "atan"]:
            try:
                num = float(calc_state.current_input)
                
                # 转换为弧度
                if not calc_state.is_radians and value in ["sin", "cos", "tan"]:
                    num = math.radians(num)
                
                if value == "sin":
                    result = math.sin(num)
                elif value == "cos":
                    result = math.cos(num)
                elif value == "tan":
                    result = math.tan(num)
                elif value == "asin":
                    result = math.asin(num)
                elif value == "acos":
                    result = math.acos(num)
                elif value == "atan":
                    result = math.atan(num)
                
                # 反三角函数结果转换为角度
                if not calc_state.is_radians and value in ["asin", "acos", "atan"]:
                    result = math.degrees(result)
                
                calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 对数函数
        elif value == "log10":
            try:
                num = float(calc_state.current_input)
                if num <= 0:
                    calc_state.error_message = "无效输入"
                else:
                    result = math.log10(num)
                    calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        elif value == "ln":
            try:
                num = float(calc_state.current_input)
                if num <= 0:
                    calc_state.error_message = "无效输入"
                else:
                    result = math.log(num)
                    calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 阶乘
        elif value == "factorial":
            try:
                num = int(float(calc_state.current_input))
                if num < 0 or num > 100:
                    calc_state.error_message = "超出范围"
                else:
                    result = math.factorial(num)
                    calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 圆周率
        elif value == "pi":
            calc_state.current_input = format_number(math.pi)
        
        # 自然常数
        elif value == "e":
            calc_state.current_input = format_number(math.e)
        
        # 弧度/角度切换
        elif value == "RAD/DEG":
            calc_state.is_radians = not calc_state.is_radians
            # 更新按钮标签
            for button in buttons:
                if button.value == "RAD/DEG":
                    button.label = "DEG" if calc_state.is_radians else "RAD"
                    break
        
        # 指数函数
        elif value == "10^x":
            try:
                num = float(calc_state.current_input)
                result = 10 ** num
                calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        elif value == "e^x":
            try:
                num = float(calc_state.current_input)
                result = math.exp(num)
                calc_state.current_input = format_number(result)
            except:
                calc_state.error_message = "错误"
        
        # 内存操作
        elif value == "MC":
            calc_state.memory = 0
        elif value == "MR":
            calc_state.current_input = format_number(calc_state.memory)
        elif value == "M+":
            try:
                calc_state.memory += float(calc_state.current_input)
            except:
                calc_state.error_message = "错误"
        elif value == "M-":
            try:
                calc_state.memory -= float(calc_state.current_input)
            except:
                calc_state.error_message = "错误"
        elif value == "MS":
            try:
                calc_state.memory = float(calc_state.current_input)
            except:
                calc_state.error_message = "错误"
        
        # 括号
        elif value in ["(", ")"]:
            calc_state.current_input += value
        
    except Exception as e:
        print(f"错误: {e}")
        calc_state.error_message = "计算错误"

def calculate_result():
    """执行计算"""
    try:
        if not calc_state.previous_input or not calc_state.operator:
            return
        
        num1 = float(calc_state.previous_input)
        num2 = float(calc_state.current_input)
        result = None
        
        if calc_state.operator == "+":
            result = num1 + num2
        elif calc_state.operator == "-":
            result = num1 - num2
        elif calc_state.operator == "*":
            result = num1 * num2
        elif calc_state.operator == "/":
            if num2 == 0:
                calc_state.error_message = "除零错误"
                return
            result = num1 / num2
        elif calc_state.operator == "^":
            result = num1 ** num2
        elif calc_state.operator == "mod":
            result = num1 % num2
        
        if result is not None:
            # 更新显示
            calc_state.current_input = format_number(result)
            calc_state.previous_input = ""
            calc_state.operator = ""
            calc_state.result = result
            calc_state.waiting_for_second = False
    
    except Exception as e:
        print(f"计算错误: {e}")
        calc_state.error_message = "计算错误"

def format_number(num):
    """格式化数字显示"""
    if isinstance(num, (int, float)):
        # 如果是整数，显示为整数
        if isinstance(num, float) and num.is_integer():
            return str(int(num))
        
        # 处理极小或极大的数字
        if abs(num) < 1e-10 and num != 0:
            return f"{num:.2e}"
        elif abs(num) > 1e10:
            return f"{num:.2e}"
        
        # 去掉末尾的零
        result = f"{num:.10f}".rstrip('0').rstrip('.')
        return result
    
    return str(num)

def main():
    """主循环"""
    clock = pygame.time.Clock()
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                
                # 检查主题按钮
                for label, value, x, y, theme_name, tooltip in theme_buttons:
                    rect = pygame.Rect(x, y, 50, 30)
                    if rect.collidepoint(mouse_pos):
                        handle_button_click(value)
                        break
                
                # 检查计算器按钮
                for button in buttons:
                    if button.rect.collidepoint(mouse_pos):
                        handle_button_click(button.value)
                        break
            
            elif event.type == pygame.KEYDOWN:
                # 键盘支持
                handle_keyboard(event.key)
        
        # 绘制界面
        screen.fill(colors["bg"])
        
        # 绘制标题
        try:
            title_surface = font_large.render("高级科学计算器", True, colors["text"])
        except:
            temp_font = pygame.font.Font(None, 42)
            title_surface = temp_font.render("高级科学计算器", True, colors["text"])
        
        screen.blit(title_surface, (WIDTH // 2 - title_surface.get_width() // 2, 10))
        
        # 绘制主题按钮
        draw_theme_buttons()
        
        # 绘制显示区域
        draw_display()
        
        # 绘制按钮
        draw_buttons()
        
        pygame.display.flip()
        clock.tick(60)

def handle_keyboard(key):
    """处理键盘输入"""
    # 数字键
    if pygame.K_0 <= key <= pygame.K_9:
        digit = str(key - pygame.K_0)
        handle_button_click(digit)
    
    # 小数点
    elif key == pygame.K_PERIOD or key == pygame.K_COMMA:
        handle_button_click(".")
    
    # 运算符
    elif key == pygame.K_PLUS or key == pygame.K_KP_PLUS:
        handle_button_click("+")
    elif key == pygame.K_MINUS or key == pygame.K_KP_MINUS:
        handle_button_click("-")
    elif key == pygame.K_ASTERISK or key == pygame.K_KP_MULTIPLY:
        handle_button_click("*")
    elif key == pygame.K_SLASH or key == pygame.K_KP_DIVIDE:
        handle_button_click("/")
    
    # 等号/回车
    elif key == pygame.K_RETURN or key == pygame.K_KP_ENTER:
        handle_button_click("=")
    
    # 退格键
    elif key == pygame.K_BACKSPACE:
        handle_button_click("DEL")
    
    # 清除键
    elif key == pygame.K_ESCAPE:
        handle_button_click("C")
    
    # 括号
    elif key == pygame.K_LEFTBRACKET:
        handle_button_click("(")
    elif key == pygame.K_RIGHTBRACKET:
        handle_button_click(")")

if __name__ == "__main__":
    main()