pytnon烟花代码
时间: 2025-10-25 07:19:04 AIGC 浏览: 4
### 使用 Matplotlib 实现简单烟花效果
为了展示如何利用 `Matplotlib` 创建动态图形来模拟烟花爆炸的效果,下面提供了一个基于时间序列更新图像的例子:
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
ln, = plt.plot([], [], 'ro', markersize=5)
def init():
ax.set_xlim(-10, 10)
ax.set_ylim(0, 20)
return ln,
def update(frame):
x_data = frame * np.cos(np.linspace(0, 2*np.pi, 36))
y_data = frame * np.sin(np.linspace(0, 2*np.pi, 36)) + frame
ln.set_data(x_data, y_data)
return ln,
ani = FuncAnimation(fig, update, frames=np.arange(0, 5, 0.1),
init_func=init, blit=True)
plt.show()
```
这段代码定义了一组随时间变化的位置数据点,并通过动画形式展现出来,模仿了烟花绽放的过程[^1]。
### 利用 Pygame 构建交互式烟花场景
对于希望构建更加复杂的视觉体验的应用程序来说,`Pygame` 提供了更好的性能和支持。这里给出一段简化版的实现方式:
```python
import pygame
import random
class Firework(pygame.sprite.Sprite):
def __init__(self, screen_rect):
super().__init__()
self.screen_rect = screen_rect
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
size = random.randint(4, 8)
self.image = pygame.Surface((size, size)).convert_alpha()
self.image.fill(color)
self.rect = self.image.get_rect(center=(random.uniform(*screen_rect.width), screen_rect.height))
self.velocity_y = -random.uniform(7, 9)
def update(self):
if not self.rect.top >= self.screen_rect.bottom:
self.rect.y += int(self.velocity_y)
self.velocity_y *= .95
elif self.alive():
self.kill()
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode([width, height])
clock = pygame.time.Clock()
all_sprites_list = pygame.sprite.Group()
for _ in range(5): all_sprites_list.add(Firework(screen.get_rect()))
running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
running = False
screen.fill((0, 0, 0))
new_fireworks = []
for sprite in all_sprites_list.sprites().copy():
if not sprite.alive() and random.random() < 0.1:
new_fireworks.append(Firework(screen.get_rect()))
all_sprites_list.update()
all_sprites_list.draw(screen)
all_sprites_list.add(new_fireworks)
pygame.display.flip()
pygame.quit()
```
此段代码展示了如何使用面向对象编程的方式管理多个独立运动的对象——即每颗“烟火”,并通过循环不断刷新屏幕上的显示内容以达到连续播放的目的.
阅读全文
