python高级烟花代码
时间: 2023-12-08 14:37:26 浏览: 243
以下是一个Python高级烟花代码的例子:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption("烟花秀")
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, 800)
self.y = random.randint(0, 200)
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.radius = 1
self.max_radius = random.randint(50, 100)
self.exploded = False
self.particles = []
def update(self):
if not self.exploded:
self.radius += 1
if self.radius >= self.max_radius:
self.explode()
else:
for particle in self.particles:
particle.update()
if all([particle.alpha <= 0 for particle in self.particles]):
fireworks.remove(self)
def draw(self):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
else:
for particle in self.particles:
particle.draw()
def explode(self):
self.exploded = True
for i in range(100):
speed = random.randint(1, 5)
direction = random.randint(0, 360)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.particles.append(Particle(self.x, self.y, speed, direction, color))
# 定义粒子类
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.alpha = 255
def update(self):
radians = self.direction * (3.14 / 180)
self.x += self.speed * round(math.cos(radians))
self.y -= self.speed * round(math.sin(radians))
self.alpha -= 5
def draw(self):
pygame.draw.circle(screen, self.color + (self.alpha,), (self.x, self.y), 5)
# 创建烟花列表
fireworks = []
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
# 按下 1 时生成一个新的烟花
if event.key == pygame.K_1:
fireworks.append(Firework())
# 按下 2 时生成 10 个烟花
if event.key == pygame.K_2:
for i in range(10):
fireworks.append(Firework())
# 更新和绘制烟花
for firework in fireworks:
firework.update()
firework.draw()
# 刷新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
阅读全文