python烟花动态代码
时间: 2023-11-16 15:01:31 浏览: 118
python程序烟花代码
5星 · 资源好评率100%
Python可以实现烟花特效,可以通过创建Trail类来定义轨迹,使用Pygame库来绘制烟花效果。下面是一个简单的烟花动态代码示例:
```python
import pygame
import random
# 定义烟花类
class Firework:
def __init__(self, x, y, size, colour):
self.colour = colour
self.trails = []
for n in range(20):
self.trails.append(Trail(n, size, True))
self.pos = vector(x, y)
self.vel = vector(0, random.uniform(-12, -8))
self.remove_firework = False
def update(self, win):
self.pos.add(self.vel)
self.vel.add(gravity)
if self.vel.y >= 0:
self.remove_firework = True
self.explode()
for trail in self.trails:
if trail.dynamic:
trail.size -= 0.2
if trail.size <= 0:
trail.size = 0
trail.colour = (trail.colour[0], trail.colour[1], trail.colour[2], trail.size * 10)
trail.show(win)
def explode(self):
for n in range(100):
self.trails.append(Trail(n, 10, False))
for trail in self.trails:
trail.get_pos(self.pos.x, self.pos.y)
trail.size = random.randint(4, 8)
trail.colour = self.colour
def remove(self):
return self.remove_firework and len(self.trails) == 0
# 定义轨迹类
class Trail:
def __init__(self, n, size, dynamic):
self.pos_in_line = n
self.pos = vector(-10, -10)
self.dynamic = dynamic
if self.dynamic:
self.colour = trail_colours[n]
self.size = int(size - n / 2)
else:
self.colour = (255, 255, 200)
self.size = size - 2
if self.size < 0:
self.size = 0
def get_pos(self, x, y):
self.pos = vector(x, y)
def show(self, win):
pygame.draw.circle(win, self.colour, (int(self.pos.x), int(self.pos.y)), self.size)
# 定义向量类
class vector:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, v):
self.x += v.x
self.y += v.y
# 定义重力向量
gravity = vector(0, 0.2)
# 定义轨迹颜色
trail_colours = [(255, 0, 0), (255, 255, 0), (0, 255, 0), (0, 255, 255), (0, 0, 255), (255, 0, 255)]
# 初始化Pygame
pygame.init()
# 设置窗口大小
win = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption("Fireworks")
# 创建烟花列表
fireworks = []
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 添加烟花
if random.randint(1, 10) == 1:
fireworks.append(Firework(random.randint(50, 750), 550, 20, (255, 255, 255)))
# 更新烟花
for fw in fireworks:
fw.update(win)
if fw.remove():
fireworks.remove(fw)
# 刷新屏幕
pygame.display.update()
```
阅读全文