表白烟花Python代码
时间: 2024-12-28 17:17:32 浏览: 11
### Python表白烟花效果实现
为了创建一个具有视觉吸引力并带有表白语句的烟花效果程序,可以采用`pygame`库。此库提供了丰富的功能用于图形绘制和动画制作。
#### 安装依赖项
首先需要安装`pygame`模块,在命令行输入如下指令完成安装:
```bash
pip install pygame
```
#### 编写表白烟花代码
以下是基于Python编写的表白烟花效果的具体实现方式[^2]:
```python
import sys, random, math
import pygame as pg
class Particle(pg.sprite.Sprite):
def __init__(self, pos, color, vel=None, acc=pg.Vector2(0, 0.1)):
super().__init__()
self.image = pg.Surface((4, 4))
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
if not vel:
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(7, 9)
vel = pg.Vector2(math.cos(angle) * speed,
math.sin(angle) * speed)
self.vel = vel
self.acc = acc
self.lifetime = 80
self.color = color
def update(self):
self.vel += self.acc
self.rect.center += self.vel
self.lifetime -= 1
if self.lifetime <= 0 or not screen.get_rect().colliderect(self.rect):
self.kill()
def create_firework(pos, num_particles, colors):
for _ in range(num_particles):
Particle(
pos=pos,
color=random.choice(colors),
vel=None)
# 初始化Pygame环境
pg.init()
screen = pg.display.set_mode((800, 600))
font = pg.font.Font(None, 50)
text_surface = font.render('我爱你,永远在一起!', True, (255, 255, 255))
text_rect = text_surface.get_rect(center=(400, 300))
particles_group = pg.sprite.Group()
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
clock = pg.time.Clock()
running = True
while running:
clock.tick(60)
for event in pg.event.get():
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
mouse_pos = pg.mouse.get_pos()
create_firework(mouse_pos, 100, colors)
elif event.type == pg.QUIT:
running = False
particles_group.update()
screen.fill((0, 0, 0))
# 居中显示表白文字
screen.blit(text_surface, text_rect)
particles_group.draw(screen)
pg.display.flip()
pg.quit()
sys.exit()
```
上述代码定义了一个粒子类`Particle`模拟单个火花的行为,并通过函数`create_firework()`批量生成这些粒子形成烟火爆炸的效果。当点击鼠标左键时触发一次烟花绽放事件;而屏幕中央始终展示着一条温馨的爱情告白信息:“我爱你,永远在一起!”
阅读全文