import pygame
import sys
from datetime import datetime, timedelta
import os

# 初始化pygame
pygame.init()

# 设置窗口尺寸
WIDTH, HEIGHT = 400, 300
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame 计时器")

# 颜色定义
BACKGROUND = (30, 30, 40)
WHITE = (255, 255, 255)
GREEN = (0, 200, 100)
RED = (220, 60, 60)
BLUE = (60, 120, 220)
GRAY = (120, 120, 120)
BUTTON_HOVER = (80, 180, 100)
BUTTON_RESET_HOVER = (80, 140, 220)

# 尝试加载中文字体


def load_fonts():
    # 常见中文字体路径列表
    chinese_font_paths = [
        # Windows 字体路径
        "C:/Windows/Fonts/msyh.ttc",           # 微软雅黑
        "C:/Windows/Fonts/simsun.ttc",         # 宋体
        "C:/Windows/Fonts/simhei.ttf",         # 黑体
        "C:/Windows/Fonts/simfang.ttf",        # 仿宋
        "C:/Windows/Fonts/simkai.ttf",         # 楷体

        # macOS 字体路径
        "/System/Library/Fonts/PingFang.ttc",  # 苹方
        "/System/Library/Fonts/STHeiti Medium.ttc",  # 华文黑体

        # Linux 字体路径
        "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
    ]

    # 检查是否存在字体文件
    for font_path in chinese_font_paths:
        if os.path.exists(font_path):
            try:
                font_large = pygame.font.Font(font_path, 72)
                font_medium = pygame.font.Font(font_path, 36)
                font_small = pygame.font.Font(font_path, 28)
                print(f"成功加载字体: {font_path}")
                return font_large, font_medium, font_small
            except Exception as e:
                print(f"加载字体失败 {font_path}: {e}")
                continue

    # 如果没有找到中文字体，使用默认字体
    print("未找到中文字体，使用默认字体")
    font_large = pygame.font.Font(None, 72)
    font_medium = pygame.font.Font(None, 36)
    font_small = pygame.font.Font(None, 28)
    return font_large, font_medium, font_small


# 加载字体
font_large, font_medium, font_small = load_fonts()

# 计时器状态


class Timer:
    def __init__(self):
        self.start_time = None
        self.elapsed_time = timedelta(0)
        self.running = False

    def start(self):
        if not self.running:
            self.running = True
            self.start_time = datetime.now()

    def pause(self):
        if self.running:
            self.running = False
            if self.start_time:
                self.elapsed_time += datetime.now() - self.start_time
                self.start_time = None

    def reset(self):
        self.running = False
        self.start_time = None
        self.elapsed_time = timedelta(0)

    def get_time(self):
        if self.running and self.start_time:
            return self.elapsed_time + (datetime.now() - self.start_time)
        return self.elapsed_time

    def format_time(self):
        total_seconds = int(self.get_time().total_seconds())
        hours = total_seconds // 3600
        minutes = (total_seconds % 3600) // 60
        seconds = total_seconds % 60
        milliseconds = int(self.get_time().microseconds / 1000)

        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
        else:
            return f"{minutes:02d}:{seconds:02d}.{milliseconds:03d}"

# 按钮类


class Button:
    def __init__(self, x, y, width, height, text, color, hover_color):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.hover_color = hover_color
        self.is_hovered = False

    def draw(self, screen):
        color = self.hover_color if self.is_hovered else self.color
        pygame.draw.rect(screen, color, self.rect, border_radius=8)
        pygame.draw.rect(screen, WHITE, self.rect, 2, border_radius=8)

        # 渲染文本，设置抗锯齿
        text_surf = font_small.render(self.text, True, WHITE)
        text_rect = text_surf.get_rect(center=self.rect.center)
        screen.blit(text_surf, text_rect)

    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)
        return self.is_hovered

    def is_clicked(self, pos, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            return self.rect.collidepoint(pos)
        return False


# 创建计时器和按钮
timer = Timer()
start_button = Button(50, 200, 100, 50, "开始", GREEN, BUTTON_HOVER)
pause_button = Button(150, 200, 100, 50, "暂停", RED, BUTTON_HOVER)
reset_button = Button(250, 200, 100, 50, "重置", BLUE, BUTTON_RESET_HOVER)

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    mouse_pos = pygame.mouse.get_pos()

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 按钮点击检测
        if start_button.is_clicked(mouse_pos, event):
            timer.start()

        if pause_button.is_clicked(mouse_pos, event):
            timer.pause()

        if reset_button.is_clicked(mouse_pos, event):
            timer.reset()

    # 更新按钮悬停状态
    start_button.check_hover(mouse_pos)
    pause_button.check_hover(mouse_pos)
    reset_button.check_hover(mouse_pos)

    # 绘制背景
    screen.fill(BACKGROUND)

    # 绘制标题
    title = font_medium.render("计时器", True, WHITE)
    screen.blit(title, (WIDTH//2 - title.get_width()//2, 20))

    # 绘制时间显示
    time_text = font_large.render(timer.format_time(), True, WHITE)
    screen.blit(time_text, (WIDTH//2 - time_text.get_width()//2, 100))

    # 绘制状态指示器
    status_text = "运行中" if timer.running else "已暂停"
    status_color = GREEN if timer.running else RED
    status = font_small.render(status_text, True, status_color)
    screen.blit(status, (WIDTH//2 - status.get_width()//2, 160))

    # 绘制按钮
    start_button.draw(screen)
    pause_button.draw(screen)
    reset_button.draw(screen)

    # 绘制底部说明
    instruction = font_small.render("点击按钮控制计时器", True, GRAY)
    screen.blit(instruction, (WIDTH//2 - instruction.get_width()//2, 260))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)  # 60 FPS

# 退出游戏
pygame.quit()
sys.exit()
