用python实现烟花效果
时间: 2023-09-24 19:07:37 浏览: 97
实现烟花效果需要用到Python的Pygame库和随机数模块。以下是一个简单的实现:
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化Pygame库
pygame.init()
# 设置窗口大小
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Fireworks")
# 循环直到用户退出程序
done = False
# 创建时钟对象
clock = pygame.time.Clock()
# 烟花粒子数量
num_particles = 50
# 烟花对象
class Firework():
def __init__(self, x, y):
self.x = x
self.y = y
self.particles = []
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
for i in range(num_particles):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
for particle in self.particles:
particle.update()
def draw(self):
for particle in self.particles:
particle.draw()
class Particle():
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.vx = random.randint(-5, 5)
self.vy = random.randint(-10, 0)
self.size = random.randint(2, 5)
self.gravity = 0.1
def update(self):
self.x += self.vx
self.y += self.vy
self.vy += self.gravity
def draw(self):
pygame.draw.circle(screen, self.color, [int(self.x), int(self.y)], self.size)
# 创建烟花列表
fireworks = []
# 游戏循环
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 当用户按下鼠标左键时发射烟花
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = event.pos
fireworks.append(Firework(x, y))
# 设置背景颜色
screen.fill(BLACK)
# 更新和绘制烟花
for firework in fireworks:
firework.update()
firework.draw()
# 移除已经消失的烟花
fireworks = [firework for firework in fireworks if len(firework.particles) > 0]
# 更新屏幕
pygame.display.flip()
# 设置帧率
clock.tick(60)
# 退出Pygame库
pygame.quit()
```
运行代码,点击鼠标左键即可发射烟花。
阅读全文