import pygame
import sys

# 分步初始化，先单独初始化字体模块
pygame.init()
pygame.font.init()

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

# 颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (30, 144, 255)

# 字体容错加载（杜绝TypeError崩溃）
try:
    # 优先尝试系统中文字体
    font_big = pygame.font.SysFont("Microsoft YaHei", 80)
    font_small = pygame.font.SysFont("Microsoft YaHei", 24)
except Exception:
    try:
        font_big = pygame.font.SysFont("SimHei", 80)
        font_small = pygame.font.SysFont("SimHei", 24)
    except Exception:
        # 兜底：使用pygame默认基础字体，纯数字完美显示
        font_big = pygame.font.Font(None, 80)
        font_small = pygame.font.Font(None, 24)

# 计时变量
clock = pygame.time.Clock()
running_ms = 0
is_run = True
FPS = 60

# 主循环
while True:
    delta = clock.tick(FPS)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                is_run = not is_run
            if event.key == pygame.K_r:
                running_ms = 0

    # 计时累加
    if is_run:
        running_ms += delta

    # 时间换算
    ms = running_ms % 1000
    s = (running_ms // 1000) % 60
    m = (running_ms // 60000) % 60
    h = running_ms // 3600000
    time_text = f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"

    # 绘制画面
    screen.fill(WHITE)
    time_surf = font_big.render(time_text, True, BLACK)
    time_rect = time_surf.get_rect(center=(WIDTH//2, HEIGHT//2 - 20))
    screen.blit(time_surf, time_rect)

    # 操作提示文字
    tip1 = font_small.render("SPACE:暂停/继续", True, BLUE)
    tip2 = font_small.render("R:重置计时器", True, BLUE)
    screen.blit(tip1, (140, HEIGHT - 70))
    screen.blit(tip2, (170, HEIGHT - 40))

    pygame.display.flip()