请写出python代码和注释
时间: 2024-02-27 12:54:55 浏览: 20
好的,以下是一个简单的基于Python的粒子动画设计代码,包括随风飘动的粒子、多个运动粒子、随机速度场和交互等功能。代码注释中会详细解释每个部分的实现。
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
# 定义粒子类
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.vx = random.uniform(-1, 1) # 随机速度
self.vy = random.uniform(-1, 1)
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 随机颜色
self.size = random.randint(5, 10) # 随机大小
self.life = 100 # 粒子生命周期
def update(self):
# 更新粒子位置
self.x += self.vx
self.y += self.vy
# 更新粒子生命周期
self.life -= 1
# 重置粒子位置和生命周期
if self.life <= 0:
self.x = random.randint(0, width)
self.y = random.randint(0, height)
self.vx = random.uniform(-1, 1)
self.vy = random.uniform(-1, 1)
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.size = random.randint(5, 10)
self.life = 100
def draw(self):
# 绘制粒子
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
# 创建多个粒子
particles = []
for i in range(50):
particles.append(Particle(random.randint(0, width), random.randint(0, height)))
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理鼠标事件
elif event.type == pygame.MOUSEMOTION:
# 使粒子围绕鼠标旋转
for p in particles:
dx = p.x - event.pos[0]
dy = p.y - event.pos[1]
dist = (dx ** 2 + dy ** 2) ** 0.5
if dist < 100:
angle = -1 * (dx / dist)
p.vx += angle * 0.1
p.vy += dy / dist * 0.1
# 清屏
screen.fill((0, 0, 0))
# 更新和绘制粒子
for p in particles:
p.update()
p.draw()
# 刷新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
以上代码实现了随机运动的粒子,多个运动粒子,随机速度场和交互等功能。其中,粒子类定义了粒子的位置、速度、颜色、大小和生命周期等属性,并实现了更新和绘制粒子的方法。游戏循环中处理了鼠标事件和粒子的更新和绘制。在处理鼠标事件时,根据鼠标位置计算出粒子与鼠标的距离和角度,并调整粒子的速度向量,使其围绕鼠标旋转。在更新和绘制粒子时,循环遍历粒子列表,更新每个粒子的位置和生命周期,并绘制粒子。最后,刷新屏幕并退出Pygame。