能写一个难一点的python烟花代码吗
时间: 2023-08-31 21:37:39 浏览: 157
### 回答1:
当然可以!这是一个用 Python 实现的烟花效果的代码示例:
```
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("烟花效果")
# 设置背景颜色
bg_color = (0, 0, 0)
# 定义烟花类
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 self.exploded:
for p in self.particles:
p.update()
# 否则,更新烟花的位置
else:
self.y -= 5
def draw(self):
# 如果烟花已经爆炸,绘制烟花碎片
if self.exploded:
for p in self.particles:
p.draw()
# 否则,绘制烟花
else:
pygame.draw.circle(screen, self.color, (self.x, self.y), 4)
# 定义烟花碎片类
class Particle:
def __init__(self, x, y, color, size):
self.x = x
self.y = y
self.color = color
self.size = size
self.gravity = 0.1
self.velocity = [random.uniform(-2, 2), random.uniform(-10, -5)]
def update(self):
self.x += self.velocity[0]
self.y += self.velocity[1]
self.velocity[1] += self.gravity
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
# 创建烟花列表
fireworks = []
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#
### 回答2:
当然可以!以下是一个稍微难一点的Python烟花代码示例:
```python
import random
import time
def generate_firework():
colors = ['red', 'green', 'blue', 'yellow', 'orange']
shapes = ['circle', 'star', 'burst', 'spark']
delays = [0.1, 0.2, 0.3, 0.4, 0.5]
color = random.choice(colors)
shape = random.choice(shapes)
delay = random.choice(delays)
return color, shape, delay
def explode_firework(color, shape):
print(f"A {color} firework explodes in a {shape} shape!")
time.sleep(1)
def light_fireworks():
print("Lighting fireworks...\n")
time.sleep(1)
for _ in range(5):
color, shape, delay = generate_firework()
explode_firework(color, shape)
time.sleep(delay)
light_fireworks()
```
这个代码会生成五个随机的烟花,并使用不同的颜色、形状和延迟时间(爆炸前的等待时间)来模拟烟花的效果。每个烟花都会在屏幕上显示其颜色和形状,然后等待一秒钟让你欣赏其美丽的爆炸效果。
阅读全文