python过年烟花代码免费
时间: 2025-01-27 14:00:45 浏览: 40
### Python代码实现烟花效果
为了创建模拟烟花的效果,可以利用`pygame`库来处理图形和动画。下面是一个简单的例子,展示了如何使用Python编写一个基本的烟花爆炸效果程序[^1]。
```python
import pygame
import random
import math
# 初始化Pygame模块
pygame.init()
# 设置屏幕大小
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
class Particle(pygame.sprite.Sprite):
"""定义粒子类"""
def __init__(self, x, y, color=(255, 255, 255)):
super().__init__()
self.image = pygame.Surface([4, 4])
self.rect = self.image.get_rect()
self.color = color
# 给定随机方向和速度
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(2, 7)
self.change_x = math.sin(angle) * speed
self.change_y = math.cos(angle) * (-speed)
self.x = x
self.y = y
def update(self):
"""更新位置并应用重力"""
self.x += self.change_x
self.y += self.change_y
self.change_y += 0.1 # 加入重力效应
self.rect.x = int(self.x)
self.rect.y = int(self.y)
def create_firework(x, y):
"""创造一组新的烟火颗粒"""
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
particles_group = pygame.sprite.Group()
for _ in range(random.randint(50, 100)):
particle_color = random.choice(colors)
new_particle = Particle(x, y, particle_color)
particles_group.add(new_particle)
return particles_group
done = False
clock = pygame.time.Clock()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
firework_particles = create_firework(mouse_pos[0], mouse_pos[1])
screen.fill((0, 0, 0))
try:
firework_particles.update()
firework_particles.draw(screen)
except AttributeError:
pass
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
这段代码通过鼠标点击触发,在屏幕上生成彩色的小圆点代表火花,并让这些点按照抛物线轨迹运动,模仿真实的烟花绽放过程[^1]。
阅读全文
相关推荐


















