以下是一个使用Python的Pygame库创建的3D立体爱心粒子效果代码: ```python import pygame import math import random from pygame.locals import * # 初始化Pygame pygame.init() # 设置窗口 width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("3D爱心粒子效果") # 颜色定义 RED = (255, 0, 0) PINK = (255, 105, 180) WHITE = (255, 255, 255) # 爱心参数 heart_particles = [] num_particles = 1000 scale = 10 speed = 0.05 # 创建爱心粒子 for _ in range(num_particles): # 3D爱心参数方程 t = random.uniform(0, 2 * math.pi) u = random.uniform(-math.pi, math.pi) x = 16 * (math.sin(t) 3) y = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t) z = 0 # 初始z坐标为0 # 添加随机偏移使粒子更自然 x += random.uniform(-0.5, 0.5) y += random.uniform(-0.5, 0.5) # 存储粒子位置和速度 heart_particles.append({ 'x': x, 'y': y, 'z': z, 'vx': random.uniform(-0.01, 0.01), 'vy': random.uniform(-0.01, 0.01), 'vz': random.uniform(0.01, 0.03), 'color': random.choice([RED, PINK, WHITE]) }) # 主循环 clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False # 清屏 screen.fill((0, 0, 0)) # 更新和绘制粒子 for particle in heart_particles: # 更新位置 particle['x'] += particle['vx'] particle['y'] += particle['vy'] particle['z'] += particle['vz'] # 如果粒子飞出屏幕,重置到爱心表面 if particle['z'] > 10: t = random.uniform(0, 2 * math.pi) particle['x'] = 16 * (math.sin(t) 3) + random.uniform(-0.5, 0.5) particle['y'] = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t) + random.uniform(-0.5, 0.5) particle['z'] = 0 particle['vz'] = random.uniform(0.01, 0.03) # 计算2D投影 size = 5 / (1 + particle['z'] * 0.2) screen_x = width // 2 + particle['x'] * scale * (1 + particle['z'] * 0.1) screen_y = height // 2 - particle['y'] * scale * (1 + particle['z'] * 0.1) # 绘制粒子 pygame.draw.circle(screen, particle['color'], (int(screen_x), int(screen_y)), int(size)) # 更新显示 pygame.display.flip() clock.tick(60) pygame.quit() ``` 代码说明: 1. 使用3D爱心参数方程生成粒子初始位置 2. 每个粒子有独立的运动速度和方向 3. 当粒子飞出屏幕后会重置到爱心表面 4. 简单的透视效果通过z坐标影响粒子大小和位置实现 运行效果: - 红色和粉色的粒子从爱心表面飞出 - 粒子大小随距离变化产生3D效果 - 粒子运动轨迹随机,形成动态效果 需要安装的库: ```bash pip install pygame ``` 三条额外需要注意的逻辑点: 1. 爱心参数方程中的t参数范围是0到2π,确保生成完整的爱心形状 2. 粒子的z坐标控制深度感知,影响其在屏幕上的投影位置和大小 3. 粒子重置逻辑确保爱心形状持续保持,不会因为粒子飞散而消失 [2025-07-23 19:30:07 | AI写代码神器 | 1015点数解答]