import pygame
import sys

# 初始化
pygame.init()
W, H = 480, 320
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("Pygame 可视化定时器")

# 解决字体报错，使用内置字体
font_large = pygame.font.Font(None, 72)
font_small = pygame.font.Font(None, 32)

# 1. 自定义定时事件：1000ms = 1秒触发一次
TIMER_TICK = pygame.USEREVENT + 1
pygame.time.set_timer(TIMER_TICK, 1000)

# 计时变量
timer_count = 0          # 定时器每秒计数
start_ms = pygame.time.get_ticks()  # 程序启动时间
clock = pygame.time.Clock()

running = True
while running:
    screen.fill((15, 15, 25))

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 每秒触发一次
        if event.type == TIMER_TICK:
            timer_count += 1

    # 计算实时总秒数
    now_ms = pygame.time.get_ticks()
    total_sec = (now_ms - start_ms) / 1000

    # 绘制文字界面
    text1 = font_large.render(f"定时计数：{timer_count}", True, (255, 255, 100))
    text2 = font_small.render(f"程序运行总秒：{total_sec:.1f}", True, (180, 220, 255))

    screen.blit(text1, (60, 80))
    screen.blit(text2, (80, 180))

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

pygame.quit()
sys.exit()