"""
===========================================
多功能计时器程序 - Pygame实现
版本: 1.0
作者: 元宝
最后更新: 2024年
===========================================
功能说明:
1. 秒表模式: 基本计时功能
2. 倒计时模式: 预设时间倒计时(1/3/5/10分钟)
3. 分段计时模式: 记录多个时间段的时间
===========================================
"""

# ==========================================
# 1. 导入模块
# ==========================================
import pygame    # 图形界面库, 用于创建GUI界面
import sys       # 系统相关功能, 用于程序退出
import time      # 时间处理模块, 用于获取时间戳
from enum import Enum  # 枚举类型, 用于定义计时器模式

# ==========================================
# 2. 初始化Pygame
# ==========================================
pygame.init()  # 初始化Pygame所有模块, 必须最先调用

# ==========================================
# 3. 窗口设置
# ==========================================
WIDTH = 800   # 窗口宽度, 单位: 像素
HEIGHT = 600  # 窗口高度, 单位: 像素
# 创建窗口对象, 参数: (宽度, 高度)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置窗口标题, 显示在窗口顶部
pygame.display.set_caption("多功能计时器 - 秒表/倒计时/分段计时")

# ==========================================
# 4. 颜色定义 (RGB格式: 红,绿,蓝, 范围0-255)
# ==========================================
# 背景颜色
BACKGROUND = (20, 25, 40)        # 深蓝色背景, 主背景色
PANEL_BG = (30, 35, 60)          # 面板背景色, 用于计时器显示区域
TEXT_COLOR = (220, 220, 240)     # 主要文字颜色, 白色偏蓝
# 强调色
ACCENT = (0, 150, 255)           # 强调色1: 蓝色, 用于标题和模式显示
ACCENT2 = (255, 100, 100)        # 强调色2: 红色, 用于警告和结束提示
ACCENT3 = (100, 255, 150)        # 强调色3: 绿色, 用于运行状态
# 按钮颜色
BUTTON_NORMAL = (50, 60, 100)    # 按钮正常状态颜色
BUTTON_HOVER = (70, 85, 130)     # 按钮鼠标悬停状态颜色
BUTTON_CLICK = (100, 120, 170)   # 按钮被点击状态颜色

# ==========================================
# 5. 模式枚举定义
# ==========================================


class TimerMode(Enum):
    """计时器模式枚举类, 定义三种计时模式"""
    STOPWATCH = 0  # 秒表模式: 正向计时, 从0开始
    COUNTDOWN = 1  # 倒计时模式: 反向计时, 从设定值到0
    LAPS = 2       # 分段计时模式: 记录多个时间段


# ==========================================
# 6. 字体设置
# ==========================================
try:
    # 尝试创建字体对象, None表示使用默认字体
    # 大字体: 72像素, 用于显示主要时间
    font_large = pygame.font.Font(None, 72)
    # 中字体: 36像素, 用于标题
    font_medium = pygame.font.Font(None, 36)
    # 小字体: 24像素, 用于按钮文字
    font_small = pygame.font.Font(None, 24)
    # 极小字体: 20像素, 用于说明文字
    font_tiny = pygame.font.Font(None, 20)
except Exception as e:
    # 如果字体创建失败, 使用系统默认字体
    print(f"字体创建失败: {e}, 使用默认字体")
    default_font = pygame.font.get_default_font()  # 获取系统默认字体
    font_large = pygame.font.Font(default_font, 72)
    font_medium = pygame.font.Font(default_font, 36)
    font_small = pygame.font.Font(default_font, 24)
    font_tiny = pygame.font.Font(default_font, 20)

# ==========================================
# 7. 按钮类定义
# ==========================================


class Button:
    """
    按钮类
    功能: 创建可交互的图形按钮
    属性: rect(矩形区域), text(按钮文字), action(点击动作)
    状态: hovered(悬停), clicked(点击)
    """

    def __init__(self, x, y, width, height, text, action=None):
        """
        初始化按钮
        参数说明:
            x: 按钮左上角X坐标(像素)
            y: 按钮左上角Y坐标(像素)
            width: 按钮宽度(像素)
            height: 按钮高度(像素)
            text: 按钮上显示的文字(字符串)
            action: 点击按钮时执行的函数(可选)
        """
        # 创建矩形对象, 定义按钮的位置和大小
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text      # 按钮文字
        self.action = action  # 点击时执行的回调函数
        self.hovered = False  # 鼠标是否悬停在按钮上(布尔值)
        self.clicked = False  # 按钮是否被点击(布尔值)

    def draw(self, surface):
        """
        在指定表面上绘制按钮
        参数:
            surface: 要绘制按钮的表面(通常是screen)
        绘制步骤:
            1. 根据状态选择颜色
            2. 绘制按钮背景
            3. 绘制按钮边框
            4. 绘制按钮文字
        """
        # 根据按钮状态选择颜色
        if self.clicked:  # 被点击状态
            color = BUTTON_CLICK
        elif self.hovered:  # 悬停状态
            color = BUTTON_HOVER
        else:  # 正常状态
            color = BUTTON_NORMAL

        # 绘制按钮背景(实心矩形, border_radius=8表示圆角半径为8像素)
        pygame.draw.rect(surface, color, self.rect, 0, border_radius=8)
        # 绘制按钮边框(宽度2像素)
        pygame.draw.rect(surface, (100, 110, 150),
                         self.rect, 2, border_radius=8)

        # 渲染按钮文字(True表示启用抗锯齿)
        text_surf = font_small.render(self.text, True, TEXT_COLOR)
        # 获取文字矩形并居中于按钮
        text_rect = text_surf.get_rect(center=self.rect.center)
        # 将文字表面绘制到按钮表面上
        surface.blit(text_surf, text_rect)

    def check_hover(self, pos):
        """
        检查鼠标是否悬停在按钮上
        参数:
            pos: 鼠标位置, 格式为(x, y)的元组
        返回:
            bool: 鼠标是否在按钮区域内
        """
        # collidepoint()检查点是否在矩形内
        self.hovered = self.rect.collidepoint(pos)
        return self.hovered  # 返回检查结果

    def handle_event(self, event):
        """
        处理鼠标事件
        参数:
            event: Pygame事件对象
        返回:
            function/None: 如果有动作要执行则返回函数, 否则返回None
        事件处理逻辑:
            1. 鼠标左键按下: 标记按钮为点击状态
            2. 鼠标左键释放: 取消点击状态
        """
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # 鼠标左键按下
            if self.hovered and self.action:  # 鼠标在按钮上且有动作函数
                self.clicked = True
                return self.action  # 返回要执行的动作函数
        elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:  # 鼠标左键释放
            self.clicked = False
        return None  # 没有事件要处理

# ==========================================
# 8. 计时器类定义
# ==========================================


class Timer:
    """
    计时器核心类
    功能: 管理所有计时逻辑和状态
    属性: mode(当前模式), running(是否运行), start_time(开始时间戳)等
    方法: start(开始), pause(暂停), reset(重置), lap(分段)等
    """

    def __init__(self):
        """
        初始化计时器
        所有时间单位: 秒
        所有时间戳: 从time.time()获取的浮点数
        """
        self.mode = TimerMode.STOPWATCH  # 当前模式, 默认为秒表模式
        self.running = False              # 计时器是否正在运行(布尔值)
        self.start_time = 0               # 开始时间的时间戳(浮点数)
        self.paused_time = 0              # 暂停时已过去的时间(浮点数)
        self.laps = []                    # 分段记录列表, 每个元素是字典
        self.countdown_duration = 300     # 倒计时时长, 默认5分钟(300秒)
        self.last_lap_time = 0            # 上一个分段的时间点(浮点数)

    def start(self):
        """
        开始计时
        功能: 启动或恢复计时器
        两种情况:
            1. 首次启动: 记录当前时间戳
            2. 从暂停恢复: 调整开始时间以继续计时
        """
        if not self.running:  # 如果计时器没有运行
            self.running = True  # 设置为运行状态
            if self.paused_time == 0:  # 首次启动(不是从暂停恢复)
                # 记录当前时间作为开始时间
                self.start_time = time.time()
            else:  # 从暂停状态恢复
                # 调整开始时间, 使计时从暂停的时间点继续
                # 公式: 新开始时间 = 当前时间 - 已暂停的时间
                self.start_time = time.time() - self.paused_time
                self.paused_time = 0  # 重置暂停时间

    def pause(self):
        """
        暂停计时
        功能: 暂停计时器, 记录已过去的时间
        只会在计时器运行时生效
        """
        if self.running:  # 如果计时器正在运行
            self.running = False  # 设置为暂停状态
            # 计算从开始到暂停经过的时间
            self.paused_time = time.time() - self.start_time

    def reset(self):
        """
        重置计时器
        功能: 将所有状态恢复到初始值
        注意: 这会清除所有分段记录
        """
        self.running = False      # 停止运行
        self.start_time = 0       # 清空开始时间
        self.paused_time = 0      # 清空暂停时间
        self.laps = []           # 清空分段记录
        self.last_lap_time = 0   # 重置上一个分段时间

    def lap(self):
        """
        记录分段
        功能: 在分段计时模式下记录一个时间段
        返回: 本段用时(浮点数)或None(如果不在分段模式或未运行)
        分段信息包含:
            - number: 分段编号(从1开始)
            - lap_time: 本段用时(当前分段)
            - total_time: 总用时(从开始到当前)
        """
        if self.running and self.mode == TimerMode.LAPS:  # 只有在运行且是分段模式
            current_time = time.time() - self.start_time  # 计算当前总时间
            lap_time = current_time - self.last_lap_time  # 计算本段用时
            # 添加分段记录到列表
            self.laps.append({
                'number': len(self.laps) + 1,  # 分段编号, 自动递增
                'lap_time': lap_time,          # 本段用时
                'total_time': current_time     # 当前总时间
            })
            self.last_lap_time = current_time  # 更新上一个分段时间
            return lap_time  # 返回本段用时
        return None  # 不在分段模式或未运行

    def get_current_time(self):
        """
        获取当前计时时间
        返回: 当前时间值(浮点数, 单位:秒)
        根据不同模式返回:
            - 秒表模式: 从开始到现在的秒数
            - 倒计时模式: 剩余秒数
            - 分段模式: 同秒表模式
        """
        if not self.running and self.paused_time > 0:  # 暂停状态
            return self.paused_time  # 返回暂停时的时间

        if self.running:  # 运行状态
            current = time.time() - self.start_time  # 计算已过时间
        else:  # 停止状态
            current = 0

        # 倒计时模式特殊处理
        if self.mode == TimerMode.COUNTDOWN:
            remaining = self.countdown_duration - current  # 计算剩余时间
            if remaining < 0:  # 时间到
                remaining = 0
                self.running = False  # 自动停止
            return remaining  # 返回剩余时间

        return current  # 秒表和分段模式返回已过时间

    def format_time(self, seconds):
        """
        格式化时间显示
        参数: seconds - 要格式化的秒数(浮点数)
        返回: 格式化的时间字符串
        格式:
            - 超过1小时: HH:MM:SS
            - 1小时内: MM:SS.mm (mm是百分秒)
        注意: 确保秒数不为负
        """
        if seconds < 0:  # 处理负值(防止倒计时显示负数)
            seconds = 0

        # 计算各个时间单位
        hours = int(seconds // 3600)              # 计算小时数
        minutes = int((seconds % 3600) // 60)     # 计算分钟数
        secs = int(seconds % 60)                  # 计算秒数
        millis = int((seconds - int(seconds)) * 100)  # 计算百分秒(0-99)

        if hours > 0:  # 如果超过1小时, 显示完整格式
            return f"{hours:02d}:{minutes:02d}:{secs:02d}"
        else:  # 1小时内, 显示分钟:秒.百分秒
            return f"{minutes:02d}:{secs:02d}.{millis:02d}"

# ==========================================
# 9. 绘图函数
# ==========================================


def draw_timer_display(surface, timer):
    """
    绘制主计时器显示区域
    参数:
        surface: 要绘制的表面(通常是screen)
        timer: Timer对象实例
    绘制内容:
        1. 背景面板
        2. 时间显示
        3. 模式显示
        4. 状态显示
    """
    # 1. 绘制背景面板
    # 创建面板矩形: 居中, 宽500高200
    panel_rect = pygame.Rect(WIDTH//2 - 250, 50, 500, 200)
    # 绘制面板背景(实心矩形)
    pygame.draw.rect(surface, PANEL_BG, panel_rect, 0, border_radius=12)
    # 绘制面板边框(宽度3像素)
    pygame.draw.rect(surface, (60, 70, 120), panel_rect, 3, border_radius=12)

    # 2. 获取并显示当前时间
    current_time = timer.get_current_time()  # 从计时器获取当前时间

    # 倒计时模式结束提醒
    if (timer.mode == TimerMode.COUNTDOWN and  # 倒计时模式
        current_time == 0 and                  # 时间到0
        timer.paused_time == 0 and            # 不是暂停状态
            timer.start_time > 0):                 # 已经开始过
        time_text = "时间到!"  # 倒计时结束提示
        time_color = ACCENT2   # 使用红色强调
    else:  # 正常显示时间
        time_text = timer.format_time(current_time)  # 格式化时间
        time_color = TEXT_COLOR  # 正常文字颜色

    # 渲染时间文本
    time_surf = font_large.render(time_text, True, time_color)
    time_rect = time_surf.get_rect(center=(WIDTH//2, 150))
    surface.blit(time_surf, time_rect)

    # 3. 显示当前模式
    # 模式显示文字字典
    mode_texts = {
        TimerMode.STOPWATCH: "秒表模式",  # 秒表模式显示
        # 倒计时模式显示
        TimerMode.COUNTDOWN: f"倒计时模式 ({timer.countdown_duration//60:02d}:{timer.countdown_duration%60:02d})",
        TimerMode.LAPS: "分段计时模式"  # 分段模式显示
    }

    # 获取并渲染模式文本
    mode_surf = font_small.render(mode_texts[timer.mode], True, ACCENT)
    mode_rect = mode_surf.get_rect(center=(WIDTH//2, 100))
    surface.blit(mode_surf, mode_rect)

    # 4. 显示计时器状态
    if timer.running:  # 运行状态
        status_text = "运行中"
        status_color = ACCENT3  # 绿色
    elif timer.paused_time > 0:  # 暂停状态
        status_text = "已暂停"
        status_color = ACCENT2  # 红色
    else:  # 停止状态
        status_text = "已停止"
        status_color = TEXT_COLOR  # 正常颜色

    # 渲染状态文本
    status_surf = font_small.render(status_text, True, status_color)
    status_rect = status_surf.get_rect(center=(WIDTH//2, 200))
    surface.blit(status_surf, status_rect)


def draw_laps(surface, timer):
    """
    绘制分段计时记录
    参数:
        surface: 要绘制的表面
        timer: Timer对象实例
    只在分段计时模式且有分段记录时显示
    显示最近5个分段记录
    """
    if timer.mode != TimerMode.LAPS or not timer.laps:  # 不在分段模式或没有分段
        return  # 不绘制

    # 1. 分段记录标题
    laps_title = font_medium.render("分段记录", True, ACCENT3)
    surface.blit(laps_title, (WIDTH//2 - laps_title.get_width()//2, 280))

    # 2. 显示最近5个分段记录(最多显示5个)
    for i, lap in enumerate(timer.laps[-5:]):  # 从列表末尾取最多5个
        y_pos = 320 + i * 40  # 计算垂直位置, 每项间隔40像素

        # 创建分段背景矩形
        lap_bg = pygame.Rect(WIDTH//2 - 200, y_pos, 400, 35)
        # 交替背景色, 奇数行和偶数行不同颜色
        bg_color = (40, 45, 80) if i % 2 == 0 else (35, 40, 70)
        # 绘制分段背景
        pygame.draw.rect(surface, bg_color, lap_bg, 0, border_radius=6)

        # 分段信息: 编号, 本段时间, 总时间
        lap_text = font_tiny.render(
            f"分段 {lap['number']}: {timer.format_time(lap['lap_time'])} (总计: {timer.format_time(lap['total_time'])})",
            True, TEXT_COLOR
        )
        # 居中显示分段信息
        surface.blit(
            lap_text, (WIDTH//2 - lap_text.get_width()//2, y_pos + 10))


def draw_countdown_controls(surface, timer):
    """
    绘制倒计时时间设置面板
    参数:
        surface: 要绘制的表面
        timer: Timer对象实例
    只在倒计时模式下显示
    提供4个预设时间按钮
    """
    if timer.mode != TimerMode.COUNTDOWN:  # 不在倒计时模式
        return  # 不绘制

    # 1. 控制面板背景
    panel_rect = pygame.Rect(WIDTH//2 - 200, 280, 400, 120)
    pygame.draw.rect(surface, PANEL_BG, panel_rect, 0, border_radius=10)
    pygame.draw.rect(surface, (60, 70, 120), panel_rect, 2, border_radius=10)

    # 2. 面板标题
    title = font_small.render("设置倒计时时间", True, ACCENT)
    surface.blit(title, (WIDTH//2 - title.get_width()//2, 290))

    # 3. 时间设置按钮定义
    time_buttons = [
        {"text": "1分钟", "time": 60},     # 1分钟
        {"text": "3分钟", "time": 180},    # 3分钟
        {"text": "5分钟", "time": 300},    # 5分钟
        {"text": "10分钟", "time": 600}    # 10分钟
    ]

    # 4. 绘制4个时间按钮
    for i, btn_info in enumerate(time_buttons):
        # 计算按钮位置, 水平均匀分布
        btn_x = WIDTH//2 - 180 + i * 90
        btn_y = 340
        btn_width = 80
        btn_height = 40
        btn_rect = pygame.Rect(btn_x, btn_y, btn_width, btn_height)

        # 高亮显示当前选择的时间
        if timer.countdown_duration == btn_info["time"]:
            color = BUTTON_HOVER  # 当前选择的时间
        else:
            color = BUTTON_NORMAL  # 未选择的时间

        # 绘制按钮背景
        pygame.draw.rect(surface, color, btn_rect, 0, border_radius=6)
        # 绘制按钮边框
        pygame.draw.rect(surface, (100, 110, 150),
                         btn_rect, 1, border_radius=6)

        # 绘制按钮文字
        text = font_tiny.render(btn_info["text"], True, TEXT_COLOR)
        # 居中显示文字
        text_x = btn_rect.centerx - text.get_width() // 2
        text_y = btn_rect.centery - text.get_height() // 2
        surface.blit(text, (text_x, text_y))

# ==========================================
# 10. 主函数
# ==========================================


def main():
    """
    主函数 - 程序入口点
    功能: 初始化程序, 运行主循环, 处理事件, 绘制界面
    流程:
        1. 初始化
        2. 创建对象
        3. 进入主循环
        4. 事件处理
        5. 界面绘制
        6. 退出清理
    """
    # 10.1 初始化
    clock = pygame.time.Clock()  # 创建时钟对象, 用于控制帧率
    timer = Timer()              # 创建计时器对象实例

    # 10.2 创建按钮列表
    buttons = []  # 存储所有按钮对象的列表

    # 模式选择按钮 (水平排列, 位于窗口上部)
    mode_buttons = [
        # 秒表模式按钮: 位置(50,400), 大小200x50, 点击切换到秒表模式
        Button(50, 400, 200, 50, "秒表模式",
               lambda: set_mode(TimerMode.STOPWATCH)),
        # 倒计时模式按钮: 位置(275,400), 大小200x50, 点击切换到倒计时模式
        Button(275, 400, 200, 50, "倒计时模式",
               lambda: set_mode(TimerMode.COUNTDOWN)),
        # 分段计时按钮: 位置(500,400), 大小200x50, 点击切换到分段模式
        Button(500, 400, 200, 50, "分段计时",
               lambda: set_mode(TimerMode.LAPS))
    ]

    # 控制按钮 (水平排列, 位于窗口下部)
    control_buttons = [
        # 开始/继续按钮: 调用timer.start()方法
        Button(100, 480, 120, 50, "开始/继续", timer.start),
        # 暂停按钮: 调用timer.pause()方法
        Button(250, 480, 120, 50, "暂停", timer.pause),
        # 重置按钮: 调用timer.reset()方法
        Button(400, 480, 120, 50, "重置", timer.reset),
        # 记录分段按钮: 调用timer.lap()方法
        Button(550, 480, 120, 50, "记录分段", timer.lap)
    ]

    # 将两组按钮添加到按钮列表
    buttons.extend(mode_buttons)      # 添加模式按钮
    buttons.extend(control_buttons)   # 添加控制按钮

    def set_mode(mode):
        """
        切换计时器模式
        参数: mode - 要切换到的模式(TimerMode枚举值)
        功能: 切换模式时重置计时器状态
        """
        if timer.mode != mode:  # 如果当前模式与要切换的模式不同
            timer.reset()  # 重置计时器(清除所有状态)
            timer.mode = mode  # 设置新模式
            if mode == TimerMode.COUNTDOWN:  # 如果是倒计时模式
                timer.countdown_duration = 300  # 重置为默认5分钟

    # 10.3 主循环标志
    running = True  # 控制主循环是否继续运行

    # ==========================================
    # 11. 主循环
    # ==========================================
    while running:  # 游戏主循环, 每秒运行约60次
        # 11.1 获取鼠标位置
        # 返回鼠标当前位置的(x, y)坐标
        mouse_pos = pygame.mouse.get_pos()

        # ==========================================
        # 12. 事件处理
        # ==========================================
        for event in pygame.event.get():  # 遍历所有事件
            # 12.1 退出事件
            if event.type == pygame.QUIT:  # 点击窗口关闭按钮
                running = False  # 退出主循环

            # 12.2 键盘事件处理
            if event.type == pygame.KEYDOWN:  # 键盘按键按下
                if event.key == pygame.K_SPACE:  # 空格键: 开始/暂停
                    if timer.running:  # 如果正在运行
                        timer.pause()  # 暂停
                    else:  # 如果暂停或停止
                        timer.start()  # 开始或继续
                elif event.key == pygame.K_r:  # R键: 重置
                    timer.reset()  # 重置计时器
                # L键(仅分段模式): 记录分段
                elif event.key == pygame.K_l and timer.mode == TimerMode.LAPS:
                    timer.lap()  # 记录分段
                elif event.key == pygame.K_1:  # 1键: 秒表模式
                    set_mode(TimerMode.STOPWATCH)
                elif event.key == pygame.K_2:  # 2键: 倒计时模式
                    set_mode(TimerMode.COUNTDOWN)
                elif event.key == pygame.K_3:  # 3键: 分段计时模式
                    set_mode(TimerMode.LAPS)
                elif event.key == pygame.K_ESCAPE:  # ESC键: 退出程序
                    running = False

            # 12.3 鼠标事件处理(按钮点击)
            for button in buttons:  # 遍历所有按钮
                action = button.handle_event(event)  # 处理按钮事件
                if action:  # 如果有动作要执行
                    action()  # 执行按钮对应的函数(如timer.start())

            # 12.4 倒计时时间设置按钮点击处理(直接点击区域)
            if (timer.mode == TimerMode.COUNTDOWN and  # 在倒计时模式下
                event.type == pygame.MOUSEBUTTONDOWN and  # 鼠标按下
                    event.button == 1):  # 左键
                # 创建4个时间按钮的矩形区域
                time_buttons = [
                    {"rect": pygame.Rect(WIDTH//2 - 180 + i*90, 340, 80, 40),
                     "time": time}
                    for i, time in enumerate([60, 180, 300, 600])  # 4个预设时间
                ]

                # 检查鼠标点击了哪个时间按钮
                for btn in time_buttons:
                    if btn["rect"].collidepoint(mouse_pos):  # 鼠标在按钮区域内
                        timer.countdown_duration = btn["time"]  # 设置倒计时时间
                        timer.reset()  # 重置计时器

        # 11.2 更新所有按钮的悬停状态
        for button in buttons:
            button.check_hover(mouse_pos)  # 检查鼠标是否悬停在按钮上

        # ==========================================
        # 13. 绘制界面
        # ==========================================
        # 13.1 清空屏幕(用背景色填充)
        screen.fill(BACKGROUND)

        # 13.2 绘制主标题
        title = font_medium.render("多功能计时器", True, ACCENT)
        # 居中显示标题
        screen.blit(title, (WIDTH//2 - title.get_width()//2, 20))

        # 13.3 绘制快捷键提示
        shortcuts = font_tiny.render(
            "快捷键: 空格(开始/暂停)  R(重置)  L(记录分段)  1/2/3(切换模式)  ESC(退出)",
            True, (150, 150, 180)  # 灰色文字
        )
        # 居中显示在窗口底部
        screen.blit(
            shortcuts, (WIDTH//2 - shortcuts.get_width()//2, HEIGHT - 30))

        # 13.4 绘制各个组件
        draw_timer_display(screen, timer)           # 主计时器显示区域
        draw_countdown_controls(screen, timer)      # 倒计时控制面板
        draw_laps(screen, timer)                    # 分段记录显示

        # 13.5 绘制所有按钮
        for button in buttons:
            button.draw(screen)  # 绘制每个按钮

        # ==========================================
        # 14. 更新显示
        # ==========================================
        pygame.display.flip()  # 更新整个屏幕显示
        clock.tick(60)         # 控制帧率为60FPS(每秒60帧)

    # ==========================================
    # 15. 退出程序
    # ==========================================
    pygame.quit()  # 退出Pygame, 释放资源
    sys.exit()     # 退出Python程序


# ==========================================
# 16. 程序入口
# ==========================================
if __name__ == "__main__":
    """
    程序入口点
    只有直接运行此文件时才执行main()函数
    如果此文件被导入为模块则不执行
    """
    main()  # 调用主函数开始程序
