import pygame
import sys

# 初始化 Pygame
pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
DARK_GRAY = (150, 150, 150)
ORANGE = (255, 165, 0)
BLUE = (100, 149, 237)

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

# 字体设置
font = pygame.font.SysFont("microsoftyaheimicrosoftyaheiuibold", 40)
small_font = pygame.font.SysFont("microsoftyaheimicrosoftyaheiuibold", 30)

# 计算器逻辑变量
display_text = ""
buttons = [
    'C', '(', ')', '/',
    '7', '8', '9', '*',
    '4', '5', '6', '-',
    '1', '2', '3', '+',
    '0', '.', '=', 'DEL'
]

def draw_button(text, x, y, w, h, color):
    """绘制按钮并返回其矩形区域用于碰撞检测"""
    rect = pygame.Rect(x, y, w, h)
    pygame.draw.rect(screen, color, rect, border_radius=10)
    pygame.draw.rect(screen, BLACK, rect, 2, border_radius=10) # 边框
    
    # 渲染文字
    text_surf = font.render(text, True, BLACK)
    text_rect = text_surf.get_rect(center=rect.center)
    screen.blit(text_surf, text_rect)
    return rect

def main():
    global display_text
    clock = pygame.time.Clock()

    while True:
        screen.fill(WHITE)
        
        # 1. 绘制显示区域
        display_rect = pygame.Rect(10, 10, 380, 80)
        pygame.draw.rect(screen, GRAY, display_rect, border_radius=10)
        pygame.draw.rect(screen, BLACK, display_rect, 3, border_radius=10)
        
        # 渲染当前输入的文字（如果太长则截断）
        txt_surface = font.render(display_text[-15:], True, BLACK)
        screen.blit(txt_surface, (20, 30))

        # 2. 绘制按钮
        button_rects = []
        btn_w, btn_h = 80, 80
        gap = 15
        start_x, start_y = 15, 110

        for i, btn in enumerate(buttons):
            row = i // 4
            col = i % 4
            x = start_x + col * (btn_w + gap)
            y = start_y + row * (btn_h + gap)
            
            # 设置不同按钮的颜色
            color = GRAY
            if btn in ['/', '*', '-', '+', '=']:
                color = ORANGE
            elif btn == 'C' or btn == 'DEL':
                color = DARK_GRAY
            
            rect = draw_button(btn, x, y, btn_w, btn_h, color)
            button_rects.append((rect, btn))

        # 3. 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = event.pos
                for rect, btn in button_rects:
                    if rect.collidepoint(mouse_pos):
                        if btn == 'C':
                            display_text = ""
                        elif btn == 'DEL':
                            display_text = display_text[:-1]
                        elif btn == '=':
                            try:
                                # 使用 eval 计算字符串结果
                                # 注意：实际项目中 eval 有风险，此处仅作演示
                                result = eval(display_text)
                                display_text = str(result)
                            except:
                                display_text = "Error"
                        else:
                            # 如果之前是 Error，点击数字先清空
                            if display_text == "Error":
                                display_text = ""
                            display_text += btn

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

if __name__ == "__main__":
    main()