用Python写一段无限播放烟花特效代码
时间: 2023-11-19 08:11:20 浏览: 145
好的,我可以帮你写一个无限播放烟花特效的Python代码。同样需要使用pygame库来实现。以下是代码实现:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕宽高
screen_width = 600
screen_height = 600
# 创建屏幕对象
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置标题
pygame.display.set_caption("Fireworks")
# 定义一个烟花类
class Firework:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.radius = 2
self.burst_radius = 0
self.burst_speed = random.randint(1, 5)
self.burst_thickness = 2
# 更新烟花位置和半径
def update(self):
if self.burst_radius < 50:
self.burst_radius += self.burst_speed
else:
self.radius = 0
# 绘制烟花
def draw(self):
if self.radius > 0:
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
else:
pygame.draw.circle(screen, self.color, (self.x, self.y), self.burst_radius, self.burst_thickness)
# 定义一个烟花效果类
class FireworkEffect:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.fireworks = []
for i in range(30):
firework = Firework(self.x, self.y, self.color)
self.fireworks.append(firework)
# 更新烟花效果
def update(self):
for firework in self.fireworks:
firework.update()
# 绘制烟花效果
def draw(self):
for firework in self.fireworks:
firework.draw()
# 创建烟花效果列表
firework_effects = []
# 游戏主循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 鼠标左键按下
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = event.pos
firework_effect = FireworkEffect(x, y)
firework_effects.append(firework_effect)
# 填充背景颜色
screen.fill((0, 0, 0))
# 更新和绘制烟花效果
for firework_effect in firework_effects:
firework_effect.update()
firework_effect.draw()
# 刷新屏幕
pygame.display.flip()
# 如果烟花效果数量大于20,则删除最早的那个效果
if len(firework_effects) > 20:
del firework_effects[0]
# 退出pygame
pygame.quit()
```
运行代码后,可以点击鼠标左键,无限播放烟花效果。同时,如果烟花效果数量大于20,则删除最早的那个效果,保证屏幕不会过于混乱。希望能够帮到你!
阅读全文