python粒子爱心动态代码带名字
时间: 2025-02-06 07:02:16 浏览: 101
### Python 粒子系统实现动态心形图案带名字显示
为了创建一个带有名字显示的动态粒子效果的心形图案,可以利用 `pygame` 库来处理图形和动画。下面是一个完整的例子,该程序会生成一个窗口,在其中展示由粒子构成的心形,并在中心位置显示指定的名字。
#### 安装依赖库
首先安装所需的库:
```bash
pip install pygame
```
#### 创建粒子类与主循环
定义粒子的行为以及整个系统的运行逻辑:
```python
import math
import random
import sys
import pygame as pg
class Particle:
"""表示单个粒子"""
def __init__(self, pos, size=8, color=(255, 0, 0), speed=0.1):
self.x, self.y = pos
angle = (random.random() * math.pi / 4) + (-math.pi / 8)
velocity_mag = random.uniform(speed/2, speed)
self.vx = math.cos(angle) * velocity_mag
self.vy = math.sin(angle) * velocity_mag
self.size = size
self.color = color
def update(self):
"""更新粒子的位置并应用重力效应"""
self.vy += GRAVITY
self.x += self.vx
self.y += self.vy
if not (0 < int(self.x) < WIDTH and 0 < int(self.y) < HEIGHT):
particles.remove(self)
def draw(self, screen):
"""绘制当前粒子到屏幕上"""
pg.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
def heart_function(t):
"""根据参数t计算心形曲线上的坐标点"""
x = 16 * pow(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*ZOOM + WIDTH//2, y*ZOOM + HEIGHT//2
# 初始化Pygame环境变量
pg.init()
WIDTH, HEIGHT = 800, 600
screen = pg.display.set_mode((WIDTH, HEIGHT))
particles = []
GRAVITY = 0.098
FPS = 60
clock = pg.time.Clock()
name_text = "Your Name"
font = pg.font.Font(None, 74)
text_surface = font.render(name_text, True, (255, 255, 255))
text_rect = text_surface.get_rect(center=(WIDTH // 2, HEIGHT // 2))
ZOOM = 40
while True:
clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT or (
event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
pg.quit(); sys.exit()
t = pg.time.get_ticks()/10 % 360 * math.pi / 180
new_particle_pos = heart_function(t)
particles.append(Particle(new_particle_pos))
screen.fill((0, 0, 0)) # 清屏操作
for p in list(particles):
p.update()
p.draw(screen)
screen.blit(text_surface, text_rect)
pg.display.flip()[^1]
```
此代码片段实现了基于时间变化而不断发射新粒子形成连续流动的心形轨迹,并且可以在屏幕中央看到给定的文字。
阅读全文
相关推荐


















