元旦跨年烟花的 python代码
时间: 2024-12-31 18:45:17 浏览: 8
### Python代码实现新年烟花效果
为了创建一个模拟元旦跨年烟花的效果,可以使用`pygame`库来处理图形和动画。下面是一个简单的例子:
```python
import pygame
import random
import math
# 初始化Pygame
pygame.init()
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y, color):
super().__init__()
self.x = x
self.y = y
self.color = color
self.size = random.randint(4, 7)
self.angle = random.uniform(0, 2 * math.pi)
self.speed = random.uniform(2, 5)
def update(self):
self.x += self.speed * math.cos(self.angle)
self.y -= self.speed * math.sin(self.angle)
self.speed -= 0.1
if self.speed <= 0:
self.kill()
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
def create_firework(x, y):
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
particles = []
for _ in range(random.randint(50, 100)):
color = random.choice(colors)
particle = Particle(x, y, color)
particles.append(particle)
return particles
running = True
clock = pygame.time.Clock()
particles_list = []
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if random.random() < 0.02: # 控制烟花触发频率
px = random.randint(0, screen_width)
py = screen_height
new_particles = create_firework(px, py)
particles_list.extend(new_particles)
screen.fill(black)
for p in particles_list[:]:
p.update()
p.draw()
if not hasattr(p, 'alive') or not p.alive:
particles_list.remove(p)
pygame.display.flip()
clock.tick(60)
pygame.quit()
```
这段程序定义了一个粒子类用于表示单个火花,并通过随机角度和速度发射这些粒子以模仿真实的烟花爆炸场景[^1]。
阅读全文