import pygame
import math
import random
from pygame import gfxdraw

# 初始化Pygame
pygame.init()
WIDTH, HEIGHT = 1100, 780
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("复杂图形效果展示")
clock = pygame.time.Clock()

class ComplexGraphics:
    def __init__(self):
        self.time = 0
        self.particles = []
        
    def draw_gradient_background(self):
        """绘制渐变背景"""
        for y in range(HEIGHT):
            color_value = int((y / HEIGHT) * 155) + 55
            color = (color_value // 2, color_value // 3, color_value)
            pygame.draw.line(screen, color, (0, y), (WIDTH, y))

    def draw_rotating_polygon(self, center_x, center_y, sides, radius, rotation):
        """绘制旋转的多边形"""
        points = []
        for i in range(sides):
            angle = rotation + (2 * math.pi * i / sides)
            x = center_x + radius * math.cos(angle)
            y = center_y + radius * math.sin(angle)
            points.append((x, y))
        
        # 填充多边形 - 确保颜色值在0-255范围内
        r = max(0, min(255, int(128 + 127 * math.sin(self.time * 0.5))))
        g = max(0, min(255, int(128 + 127 * math.sin(self.time * 0.7 + 1))))
        b = max(0, min(255, int(128 + 127 * math.sin(self.time * 0.9 + 2))))
        color = (r, g, b)
        pygame.draw.polygon(screen, color, points, 0)
        pygame.draw.polygon(screen, (255, 220, 140), points, 2)

    def draw_spiral(self, center_x, center_y, max_radius, turns):
        """绘制螺旋线"""
        points = []
        for t in range(int(turns * 100)):
            angle = (t / 10) + self.time
            radius = (t / 100) * max_radius / turns
            x = center_x + radius * math.cos(angle)
            y = center_y + radius * math.sin(angle)
            points.append((x, y))
            
        if len(points) > 1:
            pygame.draw.lines(screen, (60, 210, 170), False, points, 2)

    def draw_moire_pattern(self, center_x, center_y):
        """绘制莫尔条纹图案"""
        for r in range(0, 280, 18):
            # 确保颜色值在0-255范围内
            red = max(0, min(255, int(168 + 87 * math.sin(r * 0.06 + self.time))))
            green = max(0, min(255, int(148 + 107 * math.sin(r * 0.09 + self.time * 0.5))))
            blue = max(0, min(255, int(188 + 67 * math.sin(r * 0.04 - self.time * 0.8))))
            color = (red, green, blue)
            pygame.gfxdraw.circle(screen, center_x, center_y, r, color)

    def draw_star_field(self):
        """绘制动态星场"""
        for _ in range(25):
            x = random.randint(0, WIDTH)
            y = random.randint(0, HEIGHT)
            size = random.randint(1, 3)
            brightness = random.randint(100, 240)
            color = (brightness, brightness, brightness)
            pygame.draw.circle(screen, color, (x, y), size)

    def create_particle_system(self, center_x, center_y):
        """创建粒子系统"""
        if len(self.particles) < 380 and random.random() < 0.38:
            angle = random.uniform(0, 2 * math.pi)
            speed = random.uniform(1, 4.5)
            particle = {
                'x': center_x,
                'y': center_y,
                'vx': speed * math.cos(angle),
                'vy': speed * math.sin(angle),
                'life': random.randint(25, 72),
                'max_life': 78,
                'size': random.randint(2, 5)
            }
            self.particles.append(particle)
        
        # 更新和绘制粒子
        for particle in self.particles[:]:
            particle['x'] += particle['vx']
            particle['y'] += particle['vy']
            particle['life'] -= 1
            
            life_ratio = particle['life'] / particle['max_life']
            alpha = max(0, min(255, int(235 * life_ratio)))
            color = (alpha, max(0, alpha - 85), max(0, alpha - 145))
            
            pygame.draw.circle(screen, color, 
                             (int(particle['x']), int(particle['y'])), 
                             max(1, int(particle['size'] * life_ratio)))
            
            if particle['life'] <= 0:
                self.particles.remove(particle)

    def draw_wave_pattern(self, amplitude=48, frequency=0.018):
        """绘制波形图案"""
        points = []
        for x in range(WIDTH):
            y = HEIGHT // 2 + amplitude * math.sin(x * frequency + self.time * 3)
            points.append((x, y))
        
        if len(points) > 1:
            pygame.draw.lines(screen, (95, 175, 225), False, points, 3)
            
            # 添加镜像波
            points2 = [(x, HEIGHT - y) for x, y in points]
            pygame.draw.lines(screen, (215, 125, 185), False, points2, 3)

    def draw_fractal_tree(self, x, y, length, angle, depth):
        """递归绘制分形树"""
        if depth == 0:
            return
        
        end_x = x + length * math.cos(angle)
        end_y = y - length * math.sin(angle)
        
        # 根据深度改变颜色 - 确保颜色值在0-255之间
        red = max(0, min(222, 132 - depth * 18))
        green = max(22, min(242, 62 + depth * 32))
        blue = max(10, min(122, 24 + depth * 16))
        color = (red, green, blue)
        
        pygame.draw.line(screen, color, (x, y), (end_x, end_y), max(1, depth))
        
        branch_length = length * 0.63
        new_depth = depth - 1
        
        # 左右分支
        self.draw_fractal_tree(end_x, end_y, branch_length, 
                              angle - 0.42 + math.sin(self.time) * 0.11, new_depth)
        self.draw_fractal_tree(end_x, end_y, branch_length, 
                              angle + 0.52 + math.cos(self.time) * 0.13, new_depth)

    def draw_hex_grid(self):
        """绘制六边形网格"""
        hex_size = 26
        offset_x = hex_size * 1.74
        offset_y = hex_size * 1.51
        
        for row in range(-1, 11):
            for col in range(-1, 17):
                x = col * offset_x + (row % 2) * offset_x / 2
                y = row * offset_y
                
                # 只在左下角区域绘制
                if x < 340 and y < 680 and x > 10 and y > 260:
                    points = []
                    for i in range(6):
                        angle = math.pi / 3 * i + math.pi / 6 + self.time * 0.01
                        px = x + hex_size * math.cos(angle)
                        py = y + hex_size * math.sin(angle)
                        points.append((px, py))
                    
                    alpha = int(55 + 44 * math.sin(x * 0.021 + y * 0.034 + self.time))
                    color = (alpha, alpha + 33, alpha + 66)
                    pygame.draw.polygon(screen, color, points, 1)

    def update(self):
        self.time += 0.014

def main():
    graphics = ComplexGraphics()
    running = True
    
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
        
        # 清屏
        screen.fill((18, 21, 29))
        
        # 绘制各种复杂图形
        graphics.draw_gradient_background()
        graphics.draw_moire_pattern(185, 385)
        graphics.draw_rotating_polygon(560, 330, 6, 135, graphics.time)
        graphics.draw_rotating_polygon(880, 440, 10, 82, -graphics.time * 0.43)
        graphics.draw_spiral(370, 630, 190, 3.6)
        graphics.draw_wave_pattern(55, 0.013)
        graphics.draw_hex_grid()
        
        # 绘制分形树
        graphics.draw_fractal_tree(980, 690, 68, -math.pi / 2, 7)
        
        # 粒子系统
        graphics.create_particle_system(
            570 + 142 * math.cos(graphics.time),
            530 + 88 * math.sin(graphics.time * 0.64)
        )
        
        # 星场
        graphics.draw_star_field()
        
        # 更新状态
        graphics.update()
        
        # 显示FPS
        font = pygame.font.Font(None, 34)
        fps_text = font.render(f"FPS: {int(clock.get_fps())}", True, (245, 162, 58))
        screen.blit(fps_text, (12, 748))
        
        pygame.display.flip()
        clock.tick(56)
    
    pygame.quit()

if __name__ == "__main__":
    main()