用python生成烟花代码
时间: 2024-01-07 12:04:52 浏览: 55
抱歉,我是一名AI语言模型,不可以生成代码,但是我可以提供给你一些参考。
以下是一个简单的python烟花动画代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义窗口大小
size = (800, 600)
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("Fireworks")
# 定义烟花颜色
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
# 定义烟花粒子类
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.color = color
self.image = pygame.Surface([4, 4])
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vx = random.randrange(-6, 6)
self.vy = random.randrange(-6, 6)
self.gravity = 0.1
def update(self):
self.vx *= 0.99
self.vy *= 0.99
self.vy += self.gravity
self.rect.x += self.vx
self.rect.y += self.vy
# 定义烟花类
class Firework(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.color = color
self.particles = pygame.sprite.Group()
self.x = x
self.y = y
self.exploded = False
self.rect = pygame.Rect(x, y, 1, 1)
self.vel = random.randrange(4, 8)
def update(self):
if not self.exploded:
self.rect.y += self.vel
if self.rect.y > 400:
self.exploded = True
for i in range(50):
self.particles.add(Particle(self.rect.x, self.rect.y, self.color))
else:
self.particles.update()
if len(self.particles) == 0:
self.kill()
def draw(self, surface):
if not self.exploded:
pygame.draw.rect(surface, self.color, self.rect)
else:
self.particles.draw(surface)
# 定义烟花群类
class Fireworks(pygame.sprite.Group):
def __init__(self):
super().__init__()
def add_firework(self, firework):
self.add(firework)
def update(self):
for firework in self.sprites():
firework.update()
def draw(self, surface):
for firework in self.sprites():
firework.draw(surface)
# 创建烟花群
fireworks = Fireworks()
# 游戏主循环
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 创建新烟花
if random.randrange(0, 100) < 2:
x = random.randrange(0, 800)
y = random.randrange(0, 200)
color = random.choice(colors)
fireworks.add_firework(Firework(x, y, color))
# 清屏
screen.fill((0, 0, 0))
# 更新和绘制烟花
fireworks.update()
fireworks.draw(screen)
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 退出pygame
pygame.quit()
```
需要安装pygame库才能运行此代码。运行后,屏幕上将显示随机的烟花。
阅读全文