import pygame

# ====================
# 初始化
# ====================
pygame.init()
WIDTH, HEIGHT = 500, 350
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("货币单位转换器")

font = pygame.font.SysFont("simhei", 28)
clock = pygame.time.Clock()

# ====================
# 汇率表
# ====================
rates = {
    "CNY": 1.0,
    "USD": 7.2,
    "EUR": 7.8
}

symbols = {
    "CNY": "¥",
    "USD": "$",
    "EUR": "€"
}

# ====================
# 状态
# ====================
input_text = ""
from_unit = "CNY"
to_unit = "USD"
result = ""

buttons = {
    "CNY": pygame.Rect(40, 120, 80, 40),
    "USD": pygame.Rect(140, 120, 80, 40),
    "EUR": pygame.Rect(240, 120, 80, 40),
}

swap_button = pygame.Rect(350, 120, 100, 40)

# ====================
# 主循环
# ====================
running = True
while running:
    screen.fill((30, 30, 40))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                input_text = input_text[:-1]
            elif event.unicode.isdigit() or event.unicode == ".":
                input_text += event.unicode

        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            for unit, rect in buttons.items():
                if rect.collidepoint(x, y):
                    from_unit = unit
            if swap_button.collidepoint(x, y):
                from_unit, to_unit = to_unit, from_unit

    # ====================
    # 计算
    # ====================
    try:
        amount = float(input_text)
        cny = amount * rates[from_unit]
        converted = cny / rates[to_unit]
        result = f"{symbols[to_unit]}{converted:.2f}"
    except:
        result = "--"

    # ====================
    # 绘制
    # ====================
    title = font.render("货币单位转换器", True, (255, 255, 255))
    screen.blit(title, (160, 20))

    prompt = font.render("输入金额:", True, (200, 200, 200))
    screen.blit(prompt, (40, 70))

    pygame.draw.rect(screen, (70, 70, 90), (180, 65, 260, 40))
    input_surface = font.render(input_text, True, (255, 255, 255))
    screen.blit(input_surface, (190, 70))

    # 货币按钮
    for unit, rect in buttons.items():
        color = (0, 200, 100) if unit == from_unit else (70, 70, 90)
        pygame.draw.rect(screen, color, rect)
        text = font.render(unit, True, (255, 255, 255))
        screen.blit(text, (rect.x + 15, rect.y + 8))

    # 转换按钮
    pygame.draw.rect(screen, (100, 100, 255), swap_button)
    swap_text = font.render(f"{from_unit} → {to_unit}", True, (255, 255, 255))
    screen.blit(swap_text, (355, 128))

    # 结果
    res = font.render(f"结果: {result}", True, (0, 255, 150))
    screen.blit(res, (40, 200))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()
