python写烟花代码
时间: 2023-12-15 22:30:33 浏览: 116
以下是一个简单的Python烟花代码示例,使用了Pygame库来实现:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Fireworks")
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, screen_width)
self.y = screen_height
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.randint(5, 20)
self.exploded = False
self.particles = []
def explode(self):
self.exploded = True
for i in range(100):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
if not self.exploded:
self.y -= self.speed
if self.y <= 200:
self.explode()
else:
for particle in self.particles:
particle.update()
def draw(self):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, int(self.y)), 5)
else:
for particle in self.particles:
particle.draw()
# 定义粒子类
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.speed = random.randint(1, 5)
self.direction = random.randint(0, 360)
self.gravity = 0.1
self.alpha = 255
def update(self):
self.alpha -= 5
if self.alpha <= 0:
self.alpha = 0
self.x += self.speed * math.cos(math.radians(self.direction))
self.y += self.speed * math.sin(math.radians(self.direction)) + self.gravity
self.speed *= 0.95
def draw(self):
pygame.draw.circle(screen, (self.color[0], self.color[1], self.color[2], self.alpha), (int(self.x), int(self.y)), 3)
# 创建烟花列表
fireworks = []
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
# 按下空格键生成新的烟花
if event.key == pygame.K_SPACE:
fireworks.append(Firework())
# 绘制背景
screen.fill((0, 0, 0))
# 更新和绘制烟花
for firework in fireworks:
firework.update()
firework.draw()
# 更新屏幕
pygame.display.update()
# 退出Pygame
pygame.quit()
```
阅读全文