python制作烟火特效
时间: 2023-09-20 18:15:10 浏览: 24
要制作烟火特效,可以使用Python的Pygame模块。下面是一个简单的示例代码:
```python
import pygame
import random
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
class Firework:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = random.choice(colors)
self.velocity = random.randint(5, 10)
self.exploded = False
self.particles = []
for i in range(50):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
if not self.exploded:
self.y -= self.velocity
if self.y <= 200:
self.exploded = True
for particle in self.particles:
particle.explode()
else:
for particle in self.particles:
particle.update()
def draw(self, surface):
if not self.exploded:
pygame.draw.circle(surface, self.color, (self.x, int(self.y)), 5)
else:
for particle in self.particles:
particle.draw(surface)
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.velocity = [random.uniform(-1, 1), random.uniform(-1, 1)]
self.gravity = 0.1
self.alpha = 255
def update(self):
self.velocity[1] += self.gravity
self.x += self.velocity[0]
self.y += self.velocity[1]
self.alpha -= 5
if self.alpha <= 0:
self.alpha = 0
def draw(self, surface):
pygame.draw.circle(surface, (self.color[0], self.color[1], self.color[2], self.alpha), (int(self.x), int(self.y)), 3)
fireworks = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
if random.random() < 0.1:
fireworks.append(Firework(random.randint(0, width), height))
for firework in fireworks:
firework.update()
firework.draw(screen)
if firework.exploded and len(firework.particles) == 0:
fireworks.remove(firework)
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
运行代码后,会在窗口中生成一些随机的烟花特效。你可以根据自己的需要进行修改和扩展。