# 在main.py文件的开头添加这一行：
import random

# 如果已经有其他导入语句，可以这样添加：
import pygame
import sys
import random  # 添加这一行
# 其他导入语句...
import pygame
import sys
import time
import math
from pygame import gfxdraw

# 初始化pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 900
SCREEN_HEIGHT = 700
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("精美定时器")
clock = pygame.time.Clock()
FPS = 60

# 颜色定义
BACKGROUND_COLOR = (20, 25, 40)
TEXT_WHITE = (255, 255, 255)
TEXT_GOLD = (255, 215, 0)
TEXT_BLUE = (100, 200, 255)
TEXT_GREEN = (100, 255, 100)
TEXT_RED = (255, 100, 100)
TEXT_PURPLE = (200, 100, 255)
BUTTON_COLOR = (50, 150, 255)
BUTTON_HOVER = (100, 200, 255)
BUTTON_DISABLED = (100, 100, 150)
INPUT_BG_COLOR = (40, 60, 80)
INPUT_BORDER_COLOR = (100, 200, 255)
PANEL_BG_COLOR = (30, 40, 60, 200)
PROGRESS_BAR_COLOR = (100, 200, 255)
PROGRESS_BG_COLOR = (50, 70, 100)
NEON_BLUE = (0, 200, 255)
NEON_GREEN = (0, 255, 100)
NEON_RED = (255, 0, 100)
NEON_PURPLE = (200, 0, 255)
NEON_YELLOW = (255, 255, 0)

# 创建字体
try:
    font_small = pygame.font.Font(None, 24)
    font_medium = pygame.font.Font(None, 36)
    font_large = pygame.font.Font(None, 48)
    font_huge = pygame.font.Font(None, 72)
    font_timer = pygame.font.Font(None, 96)
except:
    font_small = pygame.font.SysFont(None, 24)
    font_medium = pygame.font.SysFont(None, 36)
    font_large = pygame.font.SysFont(None, 48)
    font_huge = pygame.font.SysFont(None, 72)
    font_timer = pygame.font.SysFont(None, 96)

# 按钮类
class Button:
    def __init__(self, x, y, width, height, text, action=None, color=BUTTON_COLOR):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.action = action
        self.color = color
        self.hover_color = BUTTON_HOVER
        self.current_color = color
        self.hover = False
        self.disabled = False
        
    def draw(self, surface):
        color = BUTTON_DISABLED if self.disabled else (self.hover_color if self.hover else self.color)
        
        # 绘制按钮
        pygame.draw.rect(surface, color, self.rect, border_radius=10)
        pygame.draw.rect(surface, TEXT_WHITE, self.rect, 2, border_radius=10)
        
        # 绘制文字
        text_surf = font_medium.render(self.text, True, TEXT_WHITE)
        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)
        
    def check_hover(self, pos):
        self.hover = self.rect.collidepoint(pos) and not self.disabled
        return self.hover
    
    def check_click(self, pos):
        if self.rect.collidepoint(pos) and self.action and not self.disabled:
            return self.action
        return None

# 时间设置类
class TimeSet:
    def __init__(self, x, y, label, initial_value=0):
        self.x = x
        self.y = y
        self.label = label
        self.value = initial_value
        self.width = 100
        self.height = 50
        
    def draw(self, surface):
        # 绘制标签
        label_surf = font_medium.render(self.label, True, TEXT_WHITE)
        surface.blit(label_surf, (self.x, self.y))
        
        # 绘制数值框
        value_rect = pygame.Rect(self.x + 120, self.y, self.width, self.height)
        pygame.draw.rect(surface, INPUT_BG_COLOR, value_rect, border_radius=5)
        pygame.draw.rect(surface, INPUT_BORDER_COLOR, value_rect, 2, border_radius=5)
        
        # 绘制数值
        value_text = font_large.render(f"{self.value:02d}", True, TEXT_WHITE)
        value_x = self.x + 120 + (self.width - value_text.get_width()) // 2
        value_y = self.y + (self.height - value_text.get_height()) // 2
        surface.blit(value_text, (value_x, value_y))
        
        # 绘制增减按钮
        inc_rect = pygame.Rect(self.x + 120 + self.width + 10, self.y, 40, self.height)
        dec_rect = pygame.Rect(self.x + 120 - 50, self.y, 40, self.height)
        
        pygame.draw.rect(surface, BUTTON_COLOR, inc_rect, border_radius=5)
        pygame.draw.rect(surface, BUTTON_COLOR, dec_rect, border_radius=5)
        
        inc_text = font_large.render("+", True, TEXT_WHITE)
        dec_text = font_large.render("-", True, TEXT_WHITE)
        
        surface.blit(inc_text, (inc_rect.x + 12, inc_rect.y + 10))
        surface.blit(dec_text, (dec_rect.x + 12, dec_rect.y + 10))
        
        return inc_rect, dec_rect, value_rect

# 进度条类
class ProgressBar:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.progress = 0.0
        self.color = PROGRESS_BAR_COLOR
        
    def set_progress(self, progress):
        self.progress = max(0.0, min(1.0, progress))
        
    def draw(self, surface):
        # 绘制背景
        pygame.draw.rect(surface, PROGRESS_BG_COLOR, 
                        (self.x, self.y, self.width, self.height), border_radius=5)
        
        # 绘制进度
        current_width = int(self.width * self.progress)
        if current_width > 0:
            pygame.draw.rect(surface, self.color, 
                           (self.x, self.y, current_width, self.height), border_radius=5)
            
        # 绘制边框
        pygame.draw.rect(surface, TEXT_WHITE, 
                        (self.x, self.y, self.width, self.height), 2, border_radius=5)

# 动画类
class Animation:
    def __init__(self, x, y, size, color):
        self.x = x
        self.y = y
        self.size = size
        self.color = color
        self.angle = 0
        self.pulse = 0
        self.pulse_speed = 0.05
        self.active = False
        
    def update(self):
        self.angle = (self.angle + 1) % 360
        self.pulse = (self.pulse + self.pulse_speed) % (2 * math.pi)
        
    def draw(self, surface):
        if not self.active:
            return
            
        # 绘制脉冲光环
        pulse_size = self.size + math.sin(self.pulse) * 10
        for i in range(3, 0, -1):
            ring_size = pulse_size + i * 5
            alpha = 50 - i * 15
            ring_color = (*self.color[:3], alpha)
            
            pygame.draw.circle(surface, ring_color, 
                             (int(self.x), int(self.y)), int(ring_size), 3)
            
        # 绘制中心圆圈
        pygame.draw.circle(surface, self.color, 
                         (int(self.x), int(self.y)), int(self.size))

# 定时器主类
class TimerApp:
    def __init__(self):
        self.state = "stopped"  # stopped, running, paused, finished
        self.total_seconds = 0
        self.remaining_seconds = 0
        self.start_time = 0
        self.paused_time = 0
        self.preset_times = [300, 600, 900, 1800, 2700]  # 5, 10, 15, 30, 45分钟
        self.preset_labels = ["5分钟", "10分钟", "15分钟", "30分钟", "45分钟"]
        self.alarm_sound = None
        self.message = ""
        self.message_time = 0
        
        # 时间设置
        self.hours_set = TimeSet(100, 150, "小时:")
        self.minutes_set = TimeSet(100, 220, "分钟:")
        self.seconds_set = TimeSet(100, 290, "秒钟:")
        
        # 进度条
        self.progress_bar = ProgressBar(100, 400, 400, 20)
        
        # 动画
        self.timer_animation = Animation(450, 500, 30, NEON_BLUE)
        self.alarm_animation = Animation(450, 500, 40, NEON_RED)
        
        # 按钮
        self.buttons = []
        self.init_buttons()
        
    def init_buttons(self):
        """初始化按钮"""
        button_width, button_height = 120, 50
        
        # 控制按钮
        self.buttons = [
            Button(100, 450, button_width, button_height, "开始", 
                  lambda: self.start_timer(), NEON_GREEN),
            Button(240, 450, button_width, button_height, "暂停", 
                  lambda: self.pause_timer(), NEON_YELLOW),
            Button(380, 450, button_width, button_height, "重置", 
                  lambda: self.reset_timer(), NEON_RED),
            Button(520, 450, button_width, button_height, "继续", 
                  lambda: self.resume_timer(), NEON_BLUE),
            
            # 预设时间按钮
            Button(600, 150, button_width, button_height, self.preset_labels[0],
                  lambda: self.set_preset_time(0), BUTTON_COLOR),
            Button(730, 150, button_width, button_height, self.preset_labels[1],
                  lambda: self.set_preset_time(1), BUTTON_COLOR),
            Button(600, 220, button_width, button_height, self.preset_labels[2],
                  lambda: self.set_preset_time(2), BUTTON_COLOR),
            Button(730, 220, button_width, button_height, self.preset_labels[3],
                  lambda: self.set_preset_time(3), BUTTON_COLOR),
            Button(665, 290, button_width, button_height, self.preset_labels[4],
                  lambda: self.set_preset_time(4), BUTTON_COLOR),
            
            # 快速设置按钮
            Button(600, 360, 120, 40, "+1小时", 
                  lambda: self.adjust_time(3600), BUTTON_COLOR),
            Button(730, 360, 120, 40, "+1分钟", 
                  lambda: self.adjust_time(60), BUTTON_COLOR),
            Button(600, 410, 120, 40, "-1小时", 
                  lambda: self.adjust_time(-3600), BUTTON_COLOR),
            Button(730, 410, 120, 40, "-1分钟", 
                  lambda: self.adjust_time(-60), BUTTON_COLOR)
        ]
        
    def set_preset_time(self, index):
        """设置预设时间"""
        if self.state == "stopped":
            self.total_seconds = self.preset_times[index]
            self.remaining_seconds = self.total_seconds
            self.update_time_displays()
            self.show_message(f"已设置: {self.preset_labels[index]}")
            
    def adjust_time(self, seconds):
        """调整时间"""
        if self.state == "stopped":
            new_seconds = self.total_seconds + seconds
            if new_seconds >= 0:
                self.total_seconds = new_seconds
                self.remaining_seconds = new_seconds
                self.update_time_displays()
                
    def update_time_displays(self):
        """更新时间显示"""
        hours = self.total_seconds // 3600
        minutes = (self.total_seconds % 3600) // 60
        seconds = self.total_seconds % 60
        
        self.hours_set.value = hours
        self.minutes_set.value = minutes
        self.seconds_set.value = seconds
        
    def get_total_seconds_from_input(self):
        """从输入获取总秒数"""
        hours = self.hours_set.value
        minutes = self.minutes_set.value
        seconds = self.seconds_set.value
        
        return hours * 3600 + minutes * 60 + seconds
        
    def start_timer(self):
        """开始计时"""
        if self.state == "stopped":
            self.total_seconds = self.get_total_seconds_from_input()
            if self.total_seconds > 0:
                self.remaining_seconds = self.total_seconds
                self.start_time = time.time()
                self.state = "running"
                self.timer_animation.active = True
                self.alarm_animation.active = False
                self.show_message("计时开始！")
            else:
                self.show_message("请设置有效的时间！", TEXT_RED)
                
    def pause_timer(self):
        """暂停计时"""
        if self.state == "running":
            self.paused_time = time.time()
            self.state = "paused"
            self.timer_animation.active = False
            self.show_message("计时已暂停")
            
    def resume_timer(self):
        """继续计时"""
        if self.state == "paused":
            # 计算暂停的时间差
            pause_duration = time.time() - self.paused_time
            self.start_time += pause_duration
            self.state = "running"
            self.timer_animation.active = True
            self.show_message("继续计时")
            
    def reset_timer(self):
        """重置计时"""
        if self.state in ["running", "paused", "finished"]:
            self.state = "stopped"
            self.remaining_seconds = self.total_seconds
            self.timer_animation.active = False
            self.alarm_animation.active = False
            self.show_message("计时已重置")
            
    def update(self):
        """更新计时器状态"""
        current_time = time.time()
        
        # 更新动画
        self.timer_animation.update()
        self.alarm_animation.update()
        
        # 清除消息
        if self.message and current_time - self.message_time > 3:
            self.message = ""
            
        # 更新计时
        if self.state == "running":
            elapsed = current_time - self.start_time
            self.remaining_seconds = max(0, self.total_seconds - int(elapsed))
            
            # 更新进度条
            if self.total_seconds > 0:
                self.progress_bar.set_progress(elapsed / self.total_seconds)
                
            # 检查是否结束
            if self.remaining_seconds == 0:
                self.state = "finished"
                self.timer_animation.active = False
                self.alarm_animation.active = True
                self.show_message("时间到！", NEON_RED)
                
    def show_message(self, message, color=TEXT_GREEN):
        """显示消息"""
        self.message = message
        self.message_color = color
        self.message_time = time.time()
        
    def format_time(self, seconds):
        """格式化时间显示"""
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        
        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
        else:
            return f"{minutes:02d}:{seconds:02d}"
            
    def draw_background(self, surface):
        """绘制背景"""
        # 渐变背景
        for y in range(SCREEN_HEIGHT):
            ratio = y / SCREEN_HEIGHT
            r = int(BACKGROUND_COLOR[0] + ratio * 20)
            g = int(BACKGROUND_COLOR[1] + ratio * 20)
            b = int(BACKGROUND_COLOR[2] + ratio * 20)
            pygame.draw.line(surface, (r, g, b), (0, y), (SCREEN_WIDTH, y))
            
        # 装饰性元素
        for i in range(20):
            x = random.randint(0, SCREEN_WIDTH)
            y = random.randint(0, SCREEN_HEIGHT)
            size = random.randint(1, 3)
            brightness = random.randint(100, 200)
            pygame.draw.circle(surface, (brightness, brightness, brightness), 
                             (x, y), size)
            
    def draw_time_display(self, surface):
        """绘制时间显示"""
        # 时间显示面板
        time_panel = pygame.Rect(100, 50, 700, 80)
        pygame.draw.rect(surface, PANEL_BG_COLOR, time_panel, border_radius=15)
        pygame.draw.rect(surface, NEON_BLUE, time_panel, 3, border_radius=15)
        
        # 显示剩余时间
        time_text = self.format_time(self.remaining_seconds)
        
        # 根据状态选择颜色
        if self.state == "running":
            time_color = NEON_GREEN
        elif self.state == "paused":
            time_color = NEON_YELLOW
        elif self.state == "finished":
            time_color = NEON_RED
        else:
            time_color = TEXT_WHITE
            
        time_surf = font_timer.render(time_text, True, time_color)
        surface.blit(time_surf, (SCREEN_WIDTH//2 - time_surf.get_width()//2, 80))
        
    def draw_status_panel(self, surface):
        """绘制状态面板"""
        status_panel = pygame.Rect(100, 100, 700, 40)
        pygame.draw.rect(surface, PANEL_BG_COLOR, status_panel, border_radius=10)
        
        # 状态文本
        status_text = ""
        status_color = TEXT_WHITE
        
        if self.state == "stopped":
            status_text = "准备就绪"
            status_color = TEXT_WHITE
        elif self.state == "running":
            status_text = "计时中..."
            status_color = NEON_GREEN
        elif self.state == "paused":
            status_text = "已暂停"
            status_color = NEON_YELLOW
        elif self.state == "finished":
            status_text = "时间到！"
            status_color = NEON_RED
            
        status_surf = font_medium.render(status_text, True, status_color)
        surface.blit(status_surf, (SCREEN_WIDTH//2 - status_surf.get_width()//2, 110))
        
    def draw(self, surface):
        """绘制整个界面"""
        # 绘制背景
        self.draw_background(surface)
        
        # 绘制标题
        title = font_huge.render("精美定时器", True, TEXT_GOLD)
        surface.blit(title, (SCREEN_WIDTH//2 - title.get_width()//2, 20))
        
        # 绘制时间显示
        self.draw_time_display(surface)
        
        # 绘制状态面板
        self.draw_status_panel(surface)
        
        # 绘制时间设置
        self.hours_set.draw(surface)
        self.minutes_set.draw(surface)
        self.seconds_set.draw(surface)
        
        # 绘制进度条
        self.progress_bar.draw(surface)
        
        # 绘制按钮
        for button in self.buttons:
            button.draw(surface)
            
        # 绘制动画
        if self.state == "running" or self.state == "paused":
            self.timer_animation.draw(surface)
        elif self.state == "finished":
            self.alarm_animation.draw(surface)
            
        # 绘制消息
        if self.message:
            message_bg = pygame.Rect(SCREEN_WIDTH//2 - 200, 550, 400, 40)
            pygame.draw.rect(surface, PANEL_BG_COLOR, message_bg, border_radius=10)
            
            message_color = getattr(self, 'message_color', TEXT_GREEN)
            message_surf = font_medium.render(self.message, True, message_color)
            surface.blit(message_surf, (SCREEN_WIDTH//2 - message_surf.get_width()//2, 560))
            
        # 绘制说明
        instructions = [
            "使用说明:",
            "1. 设置小时、分钟、秒钟",
            "2. 点击'开始'启动定时器",
            "3. 可以使用预设时间快速设置",
            "4. 时间到会有动画提示"
        ]
        
        for i, instruction in enumerate(instructions):
            inst_text = font_small.render(instruction, True, TEXT_WHITE)
            surface.blit(inst_text, (600, 460 + i * 25))
            
    def handle_events(self):
        """处理事件"""
        mouse_pos = pygame.mouse.get_pos()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    # 检查按钮点击
                    for button in self.buttons:
                        action = button.check_click(mouse_pos)
                        if action:
                            action()
                            
                    # 检查时间设置控件
                    if self.state == "stopped":
                        # 小时设置
                        inc_rect, dec_rect, _ = self.hours_set.draw(screen)
                        if inc_rect.collidepoint(mouse_pos):
                            self.hours_set.value = min(99, self.hours_set.value + 1)
                        elif dec_rect.collidepoint(mouse_pos):
                            self.hours_set.value = max(0, self.hours_set.value - 1)
                            
                        # 分钟设置
                        inc_rect, dec_rect, _ = self.minutes_set.draw(screen)
                        if inc_rect.collidepoint(mouse_pos):
                            self.minutes_set.value = min(59, self.minutes_set.value + 1)
                        elif dec_rect.collidepoint(mouse_pos):
                            self.minutes_set.value = max(0, self.minutes_set.value - 1)
                            
                        # 秒钟设置
                        inc_rect, dec_rect, _ = self.seconds_set.draw(screen)
                        if inc_rect.collidepoint(mouse_pos):
                            self.seconds_set.value = min(59, self.seconds_set.value + 1)
                        elif dec_rect.collidepoint(mouse_pos):
                            self.seconds_set.value = max(0, self.seconds_set.value - 1)
                            
            elif event.type == pygame.MOUSEMOTION:
                # 更新按钮悬停状态
                for button in self.buttons:
                    button.check_hover(mouse_pos)
                    
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                elif event.key == pygame.K_SPACE:
                    if self.state == "running":
                        self.pause_timer()
                    elif self.state == "paused":
                        self.resume_timer()
                    elif self.state == "stopped":
                        self.start_timer()
                elif event.key == pygame.K_r:
                    self.reset_timer()

def main():
    app = TimerApp()
    
    while True:
        app.handle_events()
        app.update()
        app.draw(screen)
        pygame.display.flip()
        clock.tick(FPS)

if __name__ == "__main__":
    main()