python2025跨年烟花代码
时间: 2024-12-30 11:32:34 浏览: 35
### Python 2025 新年烟花效果代码实例
为了创建一个模拟新年烟花的效果,可以利用 `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))
pygame.display.set_caption('2025 New Year Fireworks')
class Particle:
def __init__(self, x, y):
self.x = x
self.y = y
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.size = random.randint(4, 7)
self.life = 30 + random.randint(-10, 10)
def update(self):
self.life -= 1
self.y -= 5 * (self.life / 30)**2 - 3
self.x += random.uniform(-1, 1) * (30 - self.life)
def draw(self):
if self.life > 0:
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
def create_firework():
particles = []
center_x = random.randint(100, screen_width - 100)
center_y = screen_height + 100
for _ in range(random.randint(60, 120)):
angle = random.uniform(0, 2 * math.pi)
radius = random.uniform(60, 120)
particle_x = center_x + radius * math.cos(angle)
particle_y = center_y - radius * math.sin(angle)
particles.append(Particle(particle_x, particle_y))
return particles
particles_list = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
if random.random() < 0.05: # 控制烟花发射频率
new_particles = create_firework()
particles_list.extend(new_particles)
for p in particles_list[:]:
p.update()
p.draw()
if p.life <= 0:
particles_list.remove(p)
pygame.display.flip()
pygame.time.delay(30)
pygame.quit()
```
这段程序定义了一个粒子类 `Particle` 来表示单个火花,并通过函数 `create_firework()` 创建一组从地面爆炸升空的粒子群。主循环里不断更新这些粒子的位置并绘制到屏幕上形成动态视觉效果[^1]。
阅读全文