在 Python 中,创建一个模拟烟花效果的动画可能涉及到多个库,如 matplotlib
(用于绘制)和 numpy(用于数学计算)。然而,由于 matplotlib 并不特别适合创
建复杂的动画,我们通常会使用
pygame 或 pyglet 等库来制作这样的效果。
以下是一个使用
pygame 库创建简单烟花效果的基本示例代码。请注意,这个示例
非常基础,并且没有包括所有的细节和优化。
首先,你需要安装
pygame 库(如果你还没有安装的话):
bash 复制代码
pip install pygame
然后,你可以使用以下代码来创建一个简单的烟花效果:
python 复制代码
import
pygame
import
random
import
math
#
初始化 pygame
pygame.init()
#
设置屏幕大小和标题
screen = pygame.display.set_mode((
800, 600))
pygame.display.set_caption(
"烟花效果")
#
定义颜色
WHITE = (
255, 255, 255)
BLACK = (
0, 0, 0)
#
烟花类
class
Fireworks:
def
__init__(self):
self.pos = [random.randint(
0, 800), random.randint(0, 600)]
self.velocity = [random.uniform(
-2, 2), random.uniform(2, 5)]
self.size = random.randint(
1, 5)
self.lifetime = random.randint(
50, 150)
self.age =
0
def
update(self):
self.pos[
0] += self.velocity[0]
self.pos[
1] += self.velocity[1]
self.velocity[
1] -= 0.1 # 重力
self.age +=
1
if
self.pos[1] > 600 or self.age > self.lifetime:
return
False
return
True
def
draw(self, screen):