import pygame
import sys

# 初始化 Pygame
pygame.init()

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
DARK_GRAY = (100, 100, 100)
BLUE = (70, 130, 180)
LIGHT_BLUE = (173, 216, 230)

# 窗口设置
WIDTH, HEIGHT = 400, 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame 计算器")

# 字体设置
font = pygame.font.SysFont(None, 36)
small_font = pygame.font.SysFont(None, 28)

# 计算器状态
current_input = "0"
previous_input = ""
operator = ""
result = 0
is_calculation_done = False

# 按钮定义
buttons = [
    ["C", "±", "%", "÷"],
    ["7", "8", "9", "×"],
    ["4", "5", "6", "-"],
    ["1", "2", "3", "+"],
    ["0", ".", "="]
]

# 按钮位置和大小
button_width = 80
button_height = 60
button_margin = 10
start_x = 20
start_y = 150

def draw_button(text, x, y, width, height, color=GRAY, text_color=BLACK):
    """绘制按钮"""
    pygame.draw.rect(screen, color, (x, y, width, height), 0, 5)
    pygame.draw.rect(screen, DARK_GRAY, (x, y, width, height), 2, 5)
    
    # 根据文本长度调整字体大小
    if len(text) > 1 and text not in ["C", "±", "%", "÷", "×", "="]:
        text_surface = small_font.render(text, True, text_color)
    else:
        text_surface = font.render(text, True, text_color)
    
    text_rect = text_surface.get_rect(center=(x + width/2, y + height/2))
    screen.blit(text_surface, text_rect)
    return pygame.Rect(x, y, width, height)

def draw_display():
    """绘制显示屏"""
    # 绘制显示屏背景
    pygame.draw.rect(screen, BLACK, (20, 20, WIDTH-40, 100), 0, 10)
    
    # 绘制历史表达式
    if previous_input and operator:
        history_text = f"{previous_input} {operator}"
        history_surface = small_font.render(history_text, True, LIGHT_BLUE)
        screen.blit(history_surface, (WIDTH - 40 - history_surface.get_width(), 30))
    
    # 绘制当前输入
    # 如果文本太长，缩小字体
    if len(current_input) > 12:
        display_font = pygame.font.SysFont(None, 30)
    else:
        display_font = font
    
    display_surface = display_font.render(current_input, True, WHITE)
    
    # 右对齐文本
    display_rect = display_surface.get_rect()
    display_rect.right = WIDTH - 40
    display_rect.top = 60
    
    screen.blit(display_surface, display_rect)

def draw_calculator():
    """绘制整个计算器界面"""
    screen.fill(WHITE)
    
    # 绘制显示屏
    draw_display()
    
    # 绘制按钮
    button_rects = {}
    for row_idx, row in enumerate(buttons):
        for col_idx, text in enumerate(row):
            # 处理0按钮的特殊宽度
            if text == "0":
                x = start_x
                y = start_y + row_idx * (button_height + button_margin)
                # 0按钮占两列宽度
                zero_width = button_width * 2 + button_margin
                rect = draw_button(text, x, y, zero_width, button_height)
                button_rects[text] = rect
                break
            else:
                x = start_x + col_idx * (button_width + button_margin)
                y = start_y + row_idx * (button_height + button_margin)
                
                # 设置运算符按钮的特殊颜色
                if text in ["÷", "×", "-", "+", "="]:
                    color = BLUE
                    text_color = WHITE
                elif text in ["C", "±", "%"]:
                    color = DARK_GRAY
                    text_color = WHITE
                else:
                    color = GRAY
                    text_color = BLACK
                
                rect = draw_button(text, x, y, button_width, button_height, color, text_color)
                button_rects[text] = rect
    
    return button_rects

def calculate(a, b, op):
    """执行计算"""
    try:
        a = float(a)
        b = float(b)
        
        if op == "+":
            return a + b
        elif op == "-":
            return a - b
        elif op == "×":
            return a * b
        elif op == "÷":
            if b == 0:
                return "错误"
            return a / b
        elif op == "%":
            return a * b / 100
    except:
        return "错误"

def process_button_click(text):
    """处理按钮点击"""
    global current_input, previous_input, operator, result, is_calculation_done
    
    # 如果是数字
    if text.isdigit():
        if is_calculation_done or current_input == "0" or current_input == "错误":
            current_input = text
            is_calculation_done = False
        else:
            current_input += text
    
    # 如果是小数点
    elif text == ".":
        if is_calculation_done or current_input == "错误":
            current_input = "0."
            is_calculation_done = False
        elif "." not in current_input:
            current_input += "."
    
    # 如果是清除按钮
    elif text == "C":
        current_input = "0"
        previous_input = ""
        operator = ""
        result = 0
        is_calculation_done = False
    
    # 如果是正负号切换
    elif text == "±":
        if current_input != "0" and current_input != "错误":
            if current_input[0] == "-":
                current_input = current_input[1:]
            else:
                current_input = "-" + current_input
    
    # 如果是百分比
    elif text == "%":
        if current_input != "错误":
            try:
                value = float(current_input) / 100
                current_input = str(value)
            except:
                current_input = "错误"
    
    # 如果是运算符
    elif text in ["+", "-", "×", "÷", "%"]:
        if not is_calculation_done and previous_input and operator:
            # 计算之前的表达式
            temp_result = calculate(previous_input, current_input, operator)
            previous_input = str(temp_result)
        else:
            previous_input = current_input
        
        operator = text
        current_input = "0"
        is_calculation_done = False
    
    # 如果是等号
    elif text == "=":
        if previous_input and operator and not is_calculation_done:
            result = calculate(previous_input, current_input, operator)
            previous_input = ""
            current_input = str(result)
            operator = ""
            is_calculation_done = True

def main():
    """主函数"""
    clock = pygame.time.Clock()
    
    while True:
        button_rects = draw_calculator()
        
        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 text, rect in button_rects.items():
                    if rect.collidepoint(mouse_pos):
                        process_button_click(text)
                        break
            
            elif event.type == pygame.KEYDOWN:
                # 键盘支持
                if event.key == pygame.K_0 or event.key == pygame.K_KP0:
                    process_button_click("0")
                elif event.key == pygame.K_1 or event.key == pygame.K_KP1:
                    process_button_click("1")
                elif event.key == pygame.K_2 or event.key == pygame.K_KP2:
                    process_button_click("2")
                elif event.key == pygame.K_3 or event.key == pygame.K_KP3:
                    process_button_click("3")
                elif event.key == pygame.K_4 or event.key == pygame.K_KP4:
                    process_button_click("4")
                elif event.key == pygame.K_5 or event.key == pygame.K_KP5:
                    process_button_click("5")
                elif event.key == pygame.K_6 or event.key == pygame.K_KP6:
                    process_button_click("6")
                elif event.key == pygame.K_7 or event.key == pygame.K_KP7:
                    process_button_click("7")
                elif event.key == pygame.K_8 or event.key == pygame.K_KP8:
                    process_button_click("8")
                elif event.key == pygame.K_9 or event.key == pygame.K_KP9:
                    process_button_click("9")
                elif event.key == pygame.K_PERIOD or event.key == pygame.K_KP_PERIOD:
                    process_button_click(".")
                elif event.key == pygame.K_PLUS or event.key == pygame.K_KP_PLUS:
                    process_button_click("+")
                elif event.key == pygame.K_MINUS or event.key == pygame.K_KP_MINUS:
                    process_button_click("-")
                elif event.key == pygame.K_ASTERISK or event.key == pygame.K_KP_MULTIPLY:
                    process_button_click("×")
                elif event.key == pygame.K_SLASH or event.key == pygame.K_KP_DIVIDE:
                    process_button_click("÷")
                elif event.key == pygame.K_EQUALS or event.key == pygame.K_KP_EQUALS or event.key == pygame.K_RETURN or event.key == pygame.K_KP_ENTER:
                    process_button_click("=")
                elif event.key == pygame.K_ESCAPE or event.key == pygame.K_DELETE or event.key == pygame.K_BACKSPACE:
                    process_button_click("C")
                elif event.key == pygame.K_p:
                    process_button_click("%")
        
        pygame.display.flip()
        clock.tick(60)

if __name__ == "__main__":
    main()