import pygame
import sys

# 初始化
pygame.init()

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

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (180, 180, 180)

# 字体
font = pygame.font.Font(None, 80)
tip_font = pygame.font.Font(None, 32)

# 计时变量
start_ticks = 0
total_time = 0
is_running = False

clock = pygame.time.Clock()

# 主循环
while True:
    screen.fill(BLACK)

    # 事件处理
    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:
                if not is_running:
                    is_running = True
                    start_ticks = pygame.time.get_ticks() - total_time
                else:
                    is_running = False
                    total_time = pygame.time.get_ticks() - start_ticks

            # R键重置
            if event.key == pygame.K_r:
                is_running = False
                total_time = 0
                start_ticks = 0

    # 计算时间
    if is_running:
        current = pygame.time.get_ticks() - start_ticks
    else:
        current = total_time

    # 转为 分:秒:毫秒
    ms = current % 1000
    sec = (current // 1000) % 60
    minute = (current // 60000) % 60

    # 显示时间
    time_str = f"{minute:02d}:{sec:02d}:{ms//10:02d}"
    text = font.render(time_str, True, WHITE)
    screen.blit(text, (WIDTH//2 - text.get_width()//2, 80))

    # 提示
    tip = tip_font.render("空格:开始/暂停  R:重置", True, GRAY)
    screen.blit(tip, (30, 200))

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