import pygame
import sys

# 初始化pygame
pygame.init()
WIDTH, HEIGHT = 600, 420
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("重量单位转换器")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
BLUE = (30, 120, 200)
LIGHT_BLUE = (180, 220, 255)
GRAY = (160, 160, 160)
RED = (220, 60, 60)

# 字体（兼容中文）
try:
    font_big = pygame.font.Font("simhei.ttf", 32)
    font_text = pygame.font.Font("simhei.ttf", 24)
    font_small = pygame.font.Font("simhei.ttf", 20)
except:
    font_big = pygame.font.SysFont("Microsoft YaHei", 32)
    font_text = pygame.font.SysFont("Microsoft YaHei", 24)
    font_small = pygame.font.SysFont("Microsoft YaHei", 20)

# 单位换算系数 统一基准：千克(kg)
unit_data = {
    "千克(kg)": 1,
    "克(g)": 0.001,
    "吨(t)": 1000,
    "斤": 0.5,
    "磅(lb)": 0.453592
}
unit_list = list(unit_data.keys())
select_from = 0   # 源单位下标
select_to = 1     # 目标单位下标
input_str = ""
result_text = ""

# 按钮区域
btn_from_rect = pygame.Rect(60, 120, 210, 45)
btn_to_rect = pygame.Rect(330, 120, 210, 45)
input_box = pygame.Rect(60, 200, 480, 50)
convert_btn = pygame.Rect(180, 280, 240, 55)

clock = pygame.time.Clock()

def calculate():
    """执行单位换算"""
    global result_text
    if not input_str:
        result_text = "请输入数字！"
        return
    try:
        num = float(input_str)
        base_kg = num * unit_data[unit_list[select_from]]
        output = base_kg / unit_data[unit_list[select_to]]
        result_text = f"结果：{output:.4f} {unit_list[select_to]}"
    except ValueError:
        result_text = "输入无效，请输入数字"

running = True
while running:
    screen.fill(WHITE)
    mouse_pos = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 鼠标点击
        if event.type == pygame.MOUSEBUTTONDOWN:
            if btn_from_rect.collidepoint(event.pos):
                select_from = (select_from + 1) % len(unit_list)
                calculate()
            if btn_to_rect.collidepoint(event.pos):
                select_to = (select_to + 1) % len(unit_list)
                calculate()
            if convert_btn.collidepoint(event.pos):
                calculate()

        # 键盘输入
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                input_str = input_str[:-1]
            elif event.key == pygame.K_ESCAPE:
                running = False
            else:
                char = event.unicode
                if char in "0123456789.":
                    # 防止多个小数点
                    if char == "." and "." in input_str:
                        pass
                    else:
                        input_str += char
            calculate()

    # 绘制标题
    title = font_big.render("重量单位转换器", True, BLUE)
    screen.blit(title, (WIDTH//2 - title.get_width()//2, 30))

    # 绘制来源单位按钮
    pygame.draw.rect(screen, LIGHT_BLUE, btn_from_rect, border_radius=8)
    pygame.draw.rect(screen, BLUE, btn_from_rect, 2, border_radius=8)
    text_from = font_text.render(unit_list[select_from], True, BLACK)
    screen.blit(text_from, (btn_from_rect.x+10, btn_from_rect.y+6))

    # 绘制目标单位按钮
    pygame.draw.rect(screen, LIGHT_BLUE, btn_to_rect, border_radius=8)
    pygame.draw.rect(screen, BLUE, btn_to_rect, 2, border_radius=8)
    text_to = font_text.render(unit_list[select_to], True, BLACK)
    screen.blit(text_to, (btn_to_rect.x+10, btn_to_rect.y+6))

    # 输入框
    pygame.draw.rect(screen, (245,245,245), input_box, border_radius=8)
    pygame.draw.rect(screen, GRAY, input_box, 2, border_radius=8)
    input_display = font_text.render(input_str, True, BLACK if input_str else GRAY)
    hint = font_text.render("输入数值", True, GRAY)
    if input_str:
        screen.blit(input_display, (input_box.x+12, input_box.y+8))
    else:
        screen.blit(hint, (input_box.x+12, input_box.y+8))

    # 转换按钮
    pygame.draw.rect(screen, BLUE, convert_btn, border_radius=10)
    conv_text = font_text.render("开始转换", True, WHITE)
    screen.blit(conv_text, (convert_btn.centerx - conv_text.get_width()//2, convert_btn.y+10))

    # 显示换算结果
    res_render = font_big.render(result_text, True, RED)
    screen.blit(res_render, (60, 350))

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

pygame.quit()
sys.exit()