可以帮我写一段python放烟花编程嘛
时间: 2023-08-03 09:40:11 浏览: 119
当然可以,以下是一个简单的 Python 放烟花程序,你可以尝试运行它:
```python
import random
import time
# 定义颜色常量
RED = (255, 0, 0)
ORANGE = (255, 165, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PURPLE = (128, 0, 128)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 定义烟花粒子类
class Particle:
def __init__(self, x, y, size, color):
self.x = x
self.y = y
self.size = size
self.color = color
self.speed = random.uniform(1, 5)
self.angle = random.uniform(0, 2 * 3.1415926)
self.vx = self.speed * math.cos(self.angle)
self.vy = self.speed * math.sin(self.angle)
self.alpha = 255
def update(self):
self.x += self.vx
self.y += self.vy
self.alpha -= 3
if self.alpha <= 0:
self.alpha = 0
def draw(self, screen):
pygame.draw.circle(screen, self.color + (self.alpha,), (int(self.x), int(self.y)), self.size)
# 初始化 Pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置窗口标题
pygame.display.set_caption("烟花")
# 设置背景颜色
background_color = BLACK
# 设置烟花颜色
firework_colors = [RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, WHITE]
# 设置烟花大小
firework_sizes = [2, 3, 4, 5]
# 存储烟花粒子的列表
particles = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 显示背景
screen.fill(background_color)
# 更新并绘制烟花粒子
for particle in particles:
particle.update()
particle.draw(screen)
# 产生新的烟花
if random.random() < 0.02:
x = random.uniform(0, screen_width)
y = random.uniform(0, screen_height)
color = random.choice(firework_colors)
size = random.choice(firework_sizes)
for i in range(30):
particles.append(Particle(x, y, size, color))
# 清除已经消失的烟花粒子
particles = [particle for particle in particles if particle.alpha > 0]
# 更新屏幕
pygame.display.update()
# 等待一段时间
time.sleep(0.01)
# 退出 Pygame
pygame.quit()
```
这段代码使用 Pygame 库实现了一个简单的烟花程序。它每隔一段时间产生一个新的烟花,烟花会分裂成许多粒子,并向四面八方散开,最终消失。你可以在代码中调整烟花的颜色、大小、数量和速度等参数,让它变得更加有趣。
阅读全文