酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

粒子爱心python代码

以下是一个使用Python的Pygame库创建粒子爱心效果的代码: ```python import pygame import random import math # 初始化pygame pygame.init() # 设置窗口 width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("粒子爱心") # 颜色 RED = (255, 0, 0) PINK = (255, 192, 203) WHITE = (255, 255, 255) # 粒子类 class Particle: def __init__(self, x, y): self.x = x self.y = y self.size = random.randint(2, 5) self.color = random.choice([RED, PINK]) self.speed = random.uniform(0.5, 2) self.angle = random.uniform(0, 2 * math.pi) def update(self): self.x += math.cos(self.angle) * self.speed self.y += math.sin(self.angle) * self.speed self.size -= 0.05 if self.size < 0: self.size = 0 def draw(self, surface): if self.size > 0: pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), int(self.size)) # 爱心函数 def heart_curve(t, scale=10): 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) return x * scale + width // 2, -y * scale + height // 2 # 主循环 particles = [] clock = pygame.time.Clock() running = True while running: screen.fill((0, 0, 0)) # 生成爱心粒子 for i in range(5): t = random.uniform(0, 2 * math.pi) x, y = heart_curve(t) particiles.append(Particle(x, y)) # 更新和绘制粒子 for p in particiles[:]: p.update() p.draw(screen) if p.size <= 0: particiles.remove(p) # 事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.flip() clock.tick(60) pygame.quit() ``` 代码逻辑说明: 1. 使用参数方程绘制爱心形状,粒子会沿着爱心轨迹生成 2. 每个粒子有随机大小、颜色和运动方向 3. 粒子会逐渐缩小直到消失 4. 主循环中不断生成新粒子并更新现有粒子 运行效果: - 黑色上会出现红色和粉色的粒子 - 粒子会沿着爱心形状向外扩散 - 粒子会逐渐变小直到消失 注意事项: 1. 需要安装pygame库:`pip install pygame` 2. 可以调整heart_curve函数的scale参数改变爱心大小 3. 修改range(5)中的数字可以改变粒子生成速度 [2025-05-20 19:35:45 | AI写代码神器 | 703点数解答]

相关提问