import pygame
import sys
import random
import math
from datetime import datetime

# 初始化Pygame
pygame.init()

# 屏幕设置
WINDOW_WIDTH = 900
WINDOW_HEIGHT = 650
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("双色球选号器")

# 颜色
COLORS = {
    'background': (245, 245, 245),
    'red_ball': (220, 20, 60),
    'red_ball_glow': (255, 100, 100),
    'blue_ball': (30, 144, 255),
    'blue_ball_glow': (100, 180, 255),
    'text_dark': (40, 40, 40),
    'text_light': (255, 255, 255),
    'button_bg': (70, 130, 180),
    'button_hover': (100, 160, 210),
    'button_pressed': (50, 100, 150),
    'panel_bg': (255, 255, 255, 220),
    'border': (180, 180, 180),
    'history_bg': (250, 250, 250),
}

# ========== 中文字体支持 ==========
def get_chinese_font(size):
    """获取支持中文的字体"""
    font_paths = [
        "C:/Windows/Fonts/simsun.ttc",
        "C:/Windows/Fonts/simhei.ttf",
        "C:/Windows/Fonts/msyh.ttc",
        "C:/Windows/Fonts/STKAITI.TTF",
        "/System/Library/Fonts/PingFang.ttc",
        "/System/Library/Fonts/STHeiti Light.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
    ]
    for path in font_paths:
        try:
            if pygame.font.get_init():
                return pygame.font.Font(path, size)
        except:
            continue
    return pygame.font.Font(None, size)

FONT_TITLE = get_chinese_font(48)
FONT_BALL = get_chinese_font(32)
FONT_BUTTON = get_chinese_font(28)
FONT_INFO = get_chinese_font(20)
FONT_HISTORY = get_chinese_font(18)

class LotteryBall:
    """单个彩票球"""
    def __init__(self, number, is_red=True, radius=30):
        self.number = number
        self.is_red = is_red
        self.radius = radius
        self.x = 0
        self.y = 0
        self.target_x = 0
        self.target_y = 0
        self.animating = False
        self.animation_progress = 0
        self.start_x = 0
        self.start_y = 0
    
    def set_position(self, x, y, animate=False):
        """设置位置"""
        if animate:
            self.start_x = self.x if self.x != 0 else x
            self.start_y = self.y if self.y != 0 else y
            self.target_x = x
            self.target_y = y
            self.animating = True
            self.animation_progress = 0
        else:
            self.x = x
            self.y = y
            self.target_x = x
            self.target_y = y
    
    def update_animation(self):
        """更新动画"""
        if self.animating:
            self.animation_progress += 0.08
            if self.animation_progress >= 1:
                self.animation_progress = 1
                self.animating = False
            
            # 缓动函数 (ease-out)
            t = 1 - (1 - self.animation_progress) ** 3
            self.x = self.start_x + (self.target_x - self.start_x) * t
            self.y = self.start_y + (self.target_y - self.start_y) * t - math.sin(t * math.pi) * 30
    
    def draw(self, surface):
        """绘制球"""
        color = COLORS['red_ball'] if self.is_red else COLORS['blue_ball']
        glow_color = COLORS['red_ball_glow'] if self.is_red else COLORS['blue_ball_glow']
        
        # 发光效果
        for i in range(3, 0, -1):
            alpha = 30 - i * 8
            radius = self.radius + i * 4
            glow_surf = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
            pygame.draw.circle(glow_surf, (*glow_color, alpha), (radius, radius), radius)
            surface.blit(glow_surf, (self.x - radius, self.y - radius))
        
        # 球体
        pygame.draw.circle(surface, color, (int(self.x), int(self.y)), self.radius)
        pygame.draw.circle(surface, (255, 255, 255), (int(self.x - self.radius * 0.25), 
                          int(self.y - self.radius * 0.25)), self.radius // 4)
        pygame.draw.circle(surface, (50, 50, 50), (int(self.x), int(self.y)), self.radius, 2)
        
        # 数字
        text = FONT_BALL.render(str(self.number), True, COLORS['text_light'])
        text_rect = text.get_rect(center=(int(self.x), int(self.y)))
        surface.blit(text, text_rect)

class DoubleColorBall:
    """双色球选号器"""
    def __init__(self):
        self.red_balls = []
        self.blue_ball = None
        self.history = []
        self.is_animating = False
        self.animation_timer = 0
        self.selected_red = []
        self.selected_blue = None
        
        # 按钮
        self.generate_button = Button(350, 480, 200, 55, "生成号码", COLORS['button_bg'])
        self.clear_button = Button(570, 480, 120, 55, "清空历史", COLORS['button_bg'])
        
        # 初始化显示
        self.generate_numbers()
    
    def generate_numbers(self):
        """生成一组号码"""
        # 随机选6个红球 (1-33)
        red_pool = list(range(1, 34))
        self.selected_red = sorted(random.sample(red_pool, 6))
        
        # 随机选1个蓝球 (1-16)
        self.selected_blue = random.randint(1, 16)
        
        # 创建球对象
        self.red_balls = []
        for i, num in enumerate(self.selected_red):
            ball = LotteryBall(num, True, 32)
            # 计算位置 - 红球水平排列
            start_x = 120 + i * 70
            ball.set_position(start_x, 250, animate=True)
            self.red_balls.append(ball)
        
        self.blue_ball = LotteryBall(self.selected_blue, False, 32)
        self.blue_ball.set_position(600, 250, animate=True)
        
        self.is_animating = True
        self.animation_timer = 0
    
    def add_to_history(self):
        """添加到历史记录"""
        if len(self.history) >= 20:
            self.history.pop(0)
        self.history.append({
            'red': self.selected_red.copy(),
            'blue': self.selected_blue,
            'time': datetime.now().strftime("%H:%M:%S")
        })
    
    def update(self):
        """更新动画"""
        if self.is_animating:
            self.animation_timer += 1
            all_done = True
            for ball in self.red_balls:
                ball.update_animation()
                if ball.animating:
                    all_done = False
            if self.blue_ball:
                self.blue_ball.update_animation()
                if self.blue_ball.animating:
                    all_done = False
            
            if all_done and self.animation_timer > 20:
                self.is_animating = False
                self.add_to_history()
    
    def draw(self, surface):
        """绘制界面"""
        surface.fill(COLORS['background'])
        
        # 绘制标题背景
        title_bg = pygame.Surface((WINDOW_WIDTH, 80))
        title_bg.fill((200, 30, 50))
        title_bg.set_alpha(230)
        surface.blit(title_bg, (0, 0))
        
        # 标题
        title_text = FONT_TITLE.render("双色球选号器", True, (255, 255, 255))
        title_rect = title_text.get_rect(center=(WINDOW_WIDTH // 2, 40))
        surface.blit(title_text, title_rect)
        
        # 绘制面板
        panel_rect = pygame.Rect(50, 100, 800, 320)
        pygame.draw.rect(surface, (255, 255, 255), panel_rect, border_radius=15)
        pygame.draw.rect(surface, COLORS['border'], panel_rect, 2, border_radius=15)
        
        # 绘制红球区域标签
        label_red = FONT_INFO.render("红球 (1-33)", True, COLORS['red_ball'])
        surface.blit(label_red, (120, 140))
        
        # 绘制蓝球区域标签
        label_blue = FONT_INFO.render("蓝球 (1-16)", True, COLORS['blue_ball'])
        surface.blit(label_blue, (600, 140))
        
        # 绘制红球
        for ball in self.red_balls:
            ball.draw(surface)
        
        # 绘制蓝球
        if self.blue_ball:
            self.blue_ball.draw(surface)
        
        # 绘制分隔线
        pygame.draw.line(surface, COLORS['border'], (520, 150), (520, 370), 2)
        pygame.draw.line(surface, COLORS['border'], (50, 420), (850, 420), 1)
        
        # 显示期号信息
        info_text = FONT_INFO.render(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", 
                                     True, COLORS['text_dark'])
        surface.blit(info_text, (80, 440))
        
        # 绘制按钮
        self.generate_button.draw(surface)
        self.clear_button.draw(surface)
        
        # 绘制历史记录
        self.draw_history(surface)
    
    def draw_history(self, surface):
        """绘制历史记录"""
        history_x = 80
        history_y = 550
        
        # 历史记录标题
        history_title = FONT_INFO.render("最近选号历史:", True, COLORS['text_dark'])
        surface.blit(history_title, (history_x, history_y - 25))
        
        if not self.history:
            empty_text = FONT_INFO.render("暂无历史记录", True, (150, 150, 150))
            surface.blit(empty_text, (history_x, history_y + 5))
            return
        
        # 显示最近5条
        display_history = self.history[-5:]
        for i, record in enumerate(display_history):
            y_pos = history_y + i * 28
            
            # 显示序号
            index_text = FONT_HISTORY.render(f"#{len(self.history) - len(display_history) + i + 1}", 
                                            True, (150, 150, 150))
            surface.blit(index_text, (history_x, y_pos))
            
            # 显示红球
            red_text = " ".join([f"{n:02d}" for n in record['red']])
            red_surf = FONT_HISTORY.render(red_text, True, COLORS['red_ball'])
            surface.blit(red_surf, (history_x + 50, y_pos))
            
            # 显示蓝球
            blue_text = f" + {record['blue']:02d}"
            blue_surf = FONT_HISTORY.render(blue_text, True, COLORS['blue_ball'])
            surface.blit(blue_surf, (history_x + 210, y_pos))
            
            # 显示时间
            time_surf = FONT_HISTORY.render(record['time'], True, (180, 180, 180))
            surface.blit(time_surf, (history_x + 300, y_pos))

class Button:
    """按钮类"""
    def __init__(self, x, y, width, height, text, color):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.hover = False
        self.pressed = False
    
    def draw(self, surface):
        """绘制按钮"""
        color = self.color
        if self.pressed:
            color = COLORS['button_pressed']
        elif self.hover:
            color = COLORS['button_hover']
        
        pygame.draw.rect(surface, color, self.rect, border_radius=10)
        pygame.draw.rect(surface, (50, 50, 50), self.rect, 2, border_radius=10)
        
        text_surf = FONT_BUTTON.render(self.text, True, COLORS['text_light'])
        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)
    
    def handle_event(self, event):
        """处理事件"""
        if event.type == pygame.MOUSEMOTION:
            self.hover = self.rect.collidepoint(event.pos)
            if not self.hover:
                self.pressed = False
        
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1 and self.rect.collidepoint(event.pos):
                self.pressed = True
                return True
        
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1 and self.pressed:
                self.pressed = False
                if self.rect.collidepoint(event.pos):
                    return True
        return False

def main():
    clock = pygame.time.Clock()
    lottery = DoubleColorBall()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            # 处理生成按钮
            if lottery.generate_button.handle_event(event):
                if not lottery.is_animating:
                    lottery.generate_numbers()
            
            # 处理清空按钮
            if lottery.clear_button.handle_event(event):
                lottery.history = []
        
        # 更新动画
        lottery.update()
        
        # 绘制
        lottery.draw(screen)
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()