import pygame
import math
import random
import numpy as np
import os

# ===================== 全局配置 =====================
WIDTH, HEIGHT = 1200, 900
FPS = 60
clock = pygame.time.Clock()
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("超高复杂度复合动态图形")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BASE_COLORS = [(20, 80, 220), (220, 60, 100), (30, 200, 180), (230, 190, 40), (160, 70, 220)]

# 【修复字体】Windows微软雅黑系统绝对路径 + 多层兜底，彻底解决报错
try:
    # Windows系统自带微软雅黑真实路径，不用本地放文件
    font_path = os.path.join(os.environ["WINDIR"], "Fonts", "msyh.ttc")
    font = pygame.font.Font(font_path, 20)
except:
    try:
        font = pygame.font.SysFont("Microsoft YaHei", 20)
    except:
        # 终极兜底，随便一个系统自带字体，不会报错
        font = pygame.font.Font(None, 20)

# 粒子类
class Particle:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.vx = random.uniform(-1.2, 1.2)
        self.vy = random.uniform(-1.2, 1.2)
        self.life = random.randint(80, 180)
        self.max_life = self.life
        self.radius = random.uniform(1, 3.5)
        self.color = random.choice(BASE_COLORS)

    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.life -= 1
        alpha = int(255 * (self.life / self.max_life))
        r, g, b = self.color
        self.draw_color = (r, g, b, alpha)

    def draw(self, surf):
        if self.life > 0:
            s = pygame.Surface((8, 8), pygame.SRCALPHA)
            pygame.draw.circle(s, self.draw_color, (4, 4), self.radius)
            surf.blit(s, (self.x, self.y))

particle_list = []

# ===================== 工具绘图函数 =====================
# 1. 曼德博集合（分形底层背景）
def draw_mandelbrot(surface, time):
    scale = 2.2 + math.sin(time * 0.3) * 0.4
    offset_x = WIDTH / 2 + math.cos(time * 0.15) * 80
    offset_y = HEIGHT / 2 + math.sin(time * 0.12) * 60
    pixel_array = pygame.PixelArray(surface)
    step = 4
    for px in range(0, WIDTH, step):
        for py in range(0, HEIGHT, step):
            x0 = (px - offset_x) / (WIDTH / 4) * scale
            y0 = (py - offset_y) / (HEIGHT / 4) * scale
            x, y = 0, 0
            iter_cnt = 0
            max_iter = 60
            while x*x + y*y <= 4 and iter_cnt < max_iter:
                x, y = x**2 - y**2 + x0, 2*x*y + y0
                iter_cnt += 1
            if iter_cnt < max_iter:
                hue = (iter_cnt * 4 + time * 20) % 360
                r = int(127 * math.sin(math.radians(hue)) + 128)
                g = int(127 * math.sin(math.radians(hue + 120)) + 128)
                b = int(127 * math.sin(math.radians(hue + 240)) + 128)
                pixel_array[px:px+step, py:py+step] = (r, g, b, 80)
    del pixel_array

# 2. 谢尔宾斯基三角（递归嵌套）
def sierpinski(surf, p1, p2, p3, depth, color):
    if depth == 0:
        pygame.draw.polygon(surf, color, [p1, p2, p3], 1)
        return
    mid1 = ((p1[0]+p2[0])/2, (p1[1]+p2[1])/2)
    mid2 = ((p2[0]+p3[0])/2, (p2[1]+p3[1])/2)
    mid3 = ((p3[0]+p1[0])/2, (p3[1]+p1[1])/2)
    sierpinski(surf, p1, mid1, mid3, depth-1, color)
    sierpinski(surf, mid1, p2, mid2, depth-1, color)
    sierpinski(surf, mid3, mid2, p3, depth-1, color)

# 3. 黄金阿基米德螺旋点阵
def golden_spiral(surf, cx, cy, total_points, rotate_angle, color):
    golden = (1 + math.sqrt(5)) / 2
    for i in range(total_points):
        theta = i * (2 * math.pi / golden) + rotate_angle
        r = math.sqrt(i) * 2.8
        x = cx + r * math.cos(theta)
        y = cy + r * math.sin(theta)
        size = 1 + (i % 6) * 0.4
        pygame.draw.circle(surf, color, (int(x), int(y)), size)

# 4. 旋转啮合齿轮组
def draw_gear(surf, cx, cy, radius, tooth_num, tooth_h, rotation, color, width=2):
    pts = []
    for i in range(tooth_num * 2):
        ang = rotation + (i / (tooth_num*2)) * math.pi * 2
        r = radius + tooth_h if i % 2 == 0 else radius
        x = cx + r * math.cos(ang)
        y = cy + r * math.sin(ang)
        pts.append((x, y))
    pygame.draw.polygon(surf, color, pts, width)
    pygame.draw.circle(surf, color, (cx, cy), radius * 0.3, width)

# 5. 镂空多层雕花圆环
def hollow_ring_pattern(surf, cx, cy, t, base_r):
    layers = 6
    for lay in range(layers):
        r = base_r + lay * 22
        seg = 24 + lay * 4
        for i in range(seg):
            ang = (i / seg) * math.pi * 2 + t * 0.8
            wobble = math.sin(ang * 6 + t * 3) * 6
            x = cx + (r + wobble) * math.cos(ang)
            y = cy + (r + wobble) * math.sin(ang)
            pygame.draw.circle(surf, BASE_COLORS[lay % len(BASE_COLORS)], (x, y), 2, 1)

# 6. 正弦形变波浪网格
def wave_grid(surf, t):
    grid_size = 45
    offset = math.sin(t * 0.6) * 12
    for x in range(0, WIDTH, grid_size):
        pts = []
        for y in range(0, HEIGHT, 6):
            wx = x + math.sin(y * 0.03 + t) * 8 + offset
            pts.append((wx, y))
        pygame.draw.lines(surf, (80, 80, 140, 40), False, pts, 1)
    for y in range(0, HEIGHT, grid_size):
        pts = []
        for x in range(0, WIDTH, 6):
            wy = y + math.cos(x * 0.03 + t) * 8 + offset
            pts.append((x, wy))
        pygame.draw.lines(surf, (80, 80, 140, 40), False, pts, 1)

# ===================== 主循环 =====================
def main():
    global particle_list
    run = True
    time_counter = 0
    center_x, center_y = WIDTH // 2, HEIGHT // 2

    while run:
        dt = clock.tick(FPS) / 1000
        time_counter += dt
        screen.fill(BLACK)
        alpha_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)

        # 1. 底层：动态曼德博分形背景
        draw_mandelbrot(alpha_surface, time_counter)

        # 2. 正弦形变半透明网格
        wave_grid(alpha_surface, time_counter)

        # 3. 多层镂空雕花圆环
        hollow_ring_pattern(alpha_surface, center_x, center_y, time_counter, 120)

        # 4. 嵌套谢尔宾斯基三角形（多层错位旋转）
        tri_color = (255, 220, 80, 100)
        tri_p1 = (center_x, center_y - 260)
        tri_p2 = (center_x - 220, center_y + 160)
        tri_p3 = (center_x + 220, center_y + 160)
        sierpinski(alpha_surface, tri_p1, tri_p2, tri_p3, 7, tri_color)

        # 5. 双向旋转黄金螺旋
        golden_spiral(alpha_surface, center_x, center_y, 1200, time_counter, (255, 120, 180, 120))
        golden_spiral(alpha_surface, center_x, center_y, 900, -time_counter * 1.4, (100, 220, 255, 110))

        # 6. 多组啮合齿轮阵列
        gear_angle = time_counter * 1.2
        draw_gear(alpha_surface, center_x - 180, center_y - 100, 55, 18, 10, gear_angle, (255, 90, 90, 130), 2)
        draw_gear(alpha_surface, center_x + 180, center_y - 100, 42, 14, 8, -gear_angle * 1.6, (90, 255, 160, 130), 2)
        draw_gear(alpha_surface, center_x, center_y + 200, 70, 22, 12, gear_angle * 0.7, (210, 170, 255, 130), 2)

        # 7. 流光粒子系统
        if random.random() > 0.6:
            particle_list.append(Particle(center_x, center_y))
        for p in particle_list[:]:
            p.update()
            p.draw(alpha_surface)
            if p.life <= 0:
                particle_list.remove(p)

        # 渲染所有半透明图层到主画布
        screen.blit(alpha_surface, (0, 0))

        # 文字信息
        text = font.render(f"运行时间: {time_counter:.1f}s | 粒子数量:{len(particle_list)}", True, WHITE)
        screen.blit(text, (10, 10))

        pygame.display.flip()

        # 事件监听
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = False

    pygame.quit()

if __name__ == "__main__":
    main()