python放烟花的代码
时间: 2023-12-01 12:04:51 浏览: 43
以下是一个简单的Python放烟花的代码,你可以根据自己的需要进行修改和扩展:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置屏幕大小
screen = pygame.display.set_mode((800, 600))
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, 800)
self.y = random.randint(0, 600)
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
def update(self):
if not self.exploded:
self.radius += 1
if self.radius >= self.max_radius:
self.explode()
def explode(self):
self.exploded = True
for i in range(100):
sparks.append(Spark(self.x, self.y, self.color))
class Spark:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.radius = 2
self.angle = random.uniform(0, 2 * math.pi)
self.speed = random.uniform(1, 5)
def update(self):
self.x += self.speed * math.cos(self.angle)
self.y += self.speed * math.sin(self.angle)
self.radius -= 0.05
if self.radius <= 0:
sparks.remove(self)
# 初始化烟花和火花列表
fireworks = []
sparks = []
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fireworks.append(Firework())
# 更新烟花和火花
for firework in fireworks:
firework.update()
for spark in sparks:
spark.update()
# 绘制烟花和火花
screen.fill((0, 0, 0))
for firework in fireworks:
if not firework.exploded:
pygame.draw.circle(screen, firework.color, (firework.x, firework.y), firework.radius)
else:
for spark in sparks:
pygame.draw.circle(screen, spark.color, (int(spark.x), int(spark.y)), int(spark.radius))
pygame.display.update()
```