用Python写一段循环播放520烟花特效代码
时间: 2023-07-18 11:07:23 浏览: 101
用python写的烟花代码
以下是使用Pygame库编写的循环播放520烟花特效的代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("520烟花特效")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义烟花类
class Firework:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = random.choice([RED, GREEN, BLUE])
self.radius = 3
self.speed = random.randint(5, 10)
self.angle = random.uniform(0, 2 * 3.14)
self.vx = self.speed * math.cos(self.angle)
self.vy = -self.speed * math.sin(self.angle)
self.life = 50
def move(self):
self.x += self.vx
self.y += self.vy
self.vy += 0.3
self.life -= 1
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
# 定义函数来生成烟花
def create_firework():
firework = Firework(random.randint(100, 700), 500)
fireworks.append(firework)
# 创建一个烟花列表
fireworks = []
# 循环播放
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 填充背景色
screen.fill(BLACK)
# 生成烟花
create_firework()
# 移动和绘制烟花
for firework in fireworks:
firework.move()
firework.draw(screen)
if firework.life <= 0:
fireworks.remove(firework)
# 显示更新
pygame.display.update()
# 控制帧率
pygame.time.Clock().tick(60)
```
上述代码可以在Pygame环境下运行,需要安装Pygame库。运行后,会在窗口中循环播放烟花特效。
阅读全文