import pygame
import sys

# ========== 初始化 ==========
pygame.init()

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

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 60, 60)
GRAY = (100, 100, 100)

# 字体（系统默认字体）
font = pygame.font.SysFont(None, 100)
tip_font = pygame.font.SysFont(None, 36)

# 时间变量（单位：毫秒）
total_ms = 0  # 总计时
running = False  # 是否正在计时
last_tick = 0  # 上一帧时间

# ========== 主循环 ==========
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:
                # 空格：开始 / 暂停
                running = not running
                if running:
                    last_tick = pygame.time.get_ticks()
            if event.key == pygame.K_r:
                # R：重置
                total_ms = 0
                running = False

    # ========== 计时逻辑 ==========
    if running:
        now = pygame.time.get_ticks()
        delta = now - last_tick  # 时间差
        total_ms += delta
        last_tick = now

    # 转换为 分:秒
    seconds = total_ms // 1000
    minutes = seconds // 60
    sec_display = seconds % 60

    # ========== 绘制文本 ==========
    time_text = font.render(f"{minutes:02d}:{sec_display:02d}", True, WHITE)
    screen.blit(time_text, (WIDTH//2 - time_text.get_width()//2, HEIGHT//2 - 50))

    # 提示文字
    tip1 = tip_font.render("空格 = 开始/暂停", True, GRAY)
    tip2 = tip_font.render("R = 重置", True, GRAY)
    screen.blit(tip1, (20, 220))
    screen.blit(tip2, (20, 260))

    # 状态显示
    state = "运行中..." if running else "已暂停"
    state_text = tip_font.render(state, True, RED)
    screen.blit(state_text, (WIDTH - 150, 20))

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