爱心代码编程python粒子
时间: 2025-01-09 13:39:48 浏览: 0
### Python 粒子系统绘制爱心图形
在Python中实现粒子系统的爱心动画可以通过`Tkinter`库完成。下面是一个完整的示例程序,该程序创建了一个窗口,在其中显示由许多移动的小圆点组成的动态心形图案。
```python
import tkinter as tk
from math import sin, cos, pi
import random
class ParticleSystem:
def __init__(self, canvas):
self.canvas = canvas
self.particles = []
def add_particle(self, x, y):
size = random.uniform(1, 3)
color = '#%06x' % random.randint(0, 0xFFFFFF)
particle = {
'id': self.canvas.create_oval(x-size, y-size, x+size, y+size, fill=color),
'velocity_x': random.uniform(-2, 2),
'velocity_y': random.uniform(-2, 2),
'decay_rate': random.uniform(0.01, 0.05)
}
self.particles.append(particle)
def update_particles(self):
for p in self.particles[:]:
x1, y1, _, _ = self.canvas.coords(p['id'])
if not (0 <= x1 <= width and 0 <= y1 <= height):
self.canvas.delete(p['id'])
self.particles.remove(p)
continue
self.canvas.move(p['id'], p['velocity_x'], p['velocity_y'])
# Update velocity to simulate gravity or other forces
p['velocity_y'] += 0.1
# Decay over time
current_size = float(self.canvas.itemcget(p['id'], "width")) / 2
new_size = max(current_size * (1-p['decay_rate']), 0)
if new_size == 0:
self.canvas.delete(p['id'])
self.particles.remove(p)
else:
self.canvas.coords(
p['id'],
x1-new_size+current_size,
y1-new_size+current_size,
x1+new_size-current_size,
y1+new_size-current_size
)
def heart_function(t):
x = 16 * pow(sin(t), 3)
y = -(13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t))
return int(x*8 + width/2), int(y*8 + height/2)
root = tk.Tk()
canvas_width = 800
canvas_height = 600
width, height = canvas_width, canvas_height
canvas = tk.Canvas(root, width=width, height=height, bg='black')
canvas.pack()
particle_system = ParticleSystem(canvas)
points = [heart_function(t) for t in [i*pi/180 for i in range(0, 361)]]
for point in points:
particle_system.add_particle(*point)
def animate():
particle_system.update_particles()
root.after(30, animate)
animate()
tk.mainloop()
```
此代码片段定义了一个名为`ParticleSystem`的类用于管理所有的粒子对象,并提供了添加新粒子以及更新现有粒子位置的方法[^1]。 使用数学函数`heart_function()`生成一系列坐标来描绘出一颗心形路径上的点位集合;这些点作为初始位置被用来初始化各个粒子实例的位置参数。 动画通过调用`after()`方法周期性地刷新界面并调整每个粒子的速度向量和尺寸衰减率以模拟真实世界中的物理行为特性。
阅读全文