用Python编写烟花代码
时间: 2023-10-21 13:05:16 浏览: 119
以下是一个简单的烟花代码,使用Python和Pygame库实现:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口尺寸
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 定义颜色
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, color):
self.x = x
self.y = y
self.color = color
self.exploded = False
self.particles = []
# 更新烟花
def update(self):
# 如果烟花还没有爆炸
if not self.exploded:
# 生成花瓣粒子
for i in range(50):
speed = random.randint(1, 5)
direction = random.randint(0, 360)
particle = Particle(self.x, self.y, speed, direction, self.color)
self.particles.append(particle)
self.exploded = True
else:
# 更新每个花瓣粒子
for particle in self.particles:
particle.update()
# 绘制烟花
def draw(self, surface):
# 如果烟花还没有爆炸,就绘制一个小圆点
if not self.exploded:
pygame.draw.circle(surface, self.color, (self.x, self.y), 2)
else:
# 绘制每个花瓣粒子
for particle in self.particles:
particle.draw(surface)
# 定义花瓣粒子
class Particle:
def __init__(self, x, y, speed, direction, color):
self.x = x
self.y = y
self.speed = speed
self.direction = direction
self.color = color
self.size = 2
# 更新花瓣粒子
def update(self):
# 计算新的位置
radians = self.direction * (3.1415 / 180)
self.x += self.speed * math.cos(radians)
self.y -= self.speed * math.sin(radians)
self.speed -= 0.1
self.size -= 0.05
# 绘制花瓣粒子
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), int(self.size))
# 创建烟花列表
fireworks = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新每个烟花
for firework in fireworks:
firework.update()
# 移除已经结束的烟花
fireworks = [firework for firework in fireworks if not firework.exploded or len(firework.particles) > 0]
# 如果没有烟花在爆炸,就创建一个新的烟花
if len(fireworks) < 5:
x = random.randint(0, width)
y = random.randint(0, height)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
firework = Firework(x, y, color)
fireworks.append(firework)
# 绘制背景
screen.fill(BLACK)
# 绘制每个烟花
for firework in fireworks:
firework.draw(screen)
# 更新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
运行代码后,将会看到一个黑色的窗口,里面会不断的出现五彩缤纷的烟花。
阅读全文