python跨年代码动态
时间: 2024-12-28 13:25:17 浏览: 21
### Python 编写跨年动态效果代码示例
#### 使用 Pygame 实现跨年烟花秀
为了实现一个生动的跨年烟花秀,可以利用 `pygame` 库的强大功能。下面是一个完整的代码实例,该程序不仅实现了基本的烟花发射和爆炸效果,还加入了色彩渐变以及随机生成的不同形状的烟花。
```python
import pygame
import random
from math import sin, cos, radians
# 初始化 Pygame 和屏幕设置
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Happy New Year Fireworks Show')
class Particle(pygame.sprite.Sprite):
def __init__(self, x, y, color, size=10):
super().__init__()
self.image = pygame.Surface([size * 2, size * 2])
self.rect = self.image.get_rect(center=(x, y))
self.color = color
self.size = size
self.x_speed = (random.random() - 0.5) * 10
self.y_speed = -(random.random() + 0.5) * 10
def update(self):
self.rect.x += int(self.x_speed)
self.rect.y += int(self.y_speed)
self.size -= 0.1
if self.size <= 0:
self.kill()
def create_firework(x, y):
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
particles_group.empty()
for _ in range(100):
particle_color = random.choice(colors)
new_particle = Particle(x, y, particle_color)
all_sprites.add(new_particle)
all_sprites = pygame.sprite.Group()
particles_group = pygame.sprite.Group()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse_x, mouse_y = pygame.mouse.get_pos()
create_firework(mouse_x, mouse_y)
screen.fill((0, 0, 0)) # 清屏并填充黑色作为夜空背景
all_sprites.update()
for sprite in all_sprites.sprites():
pygame.draw.circle(screen, sprite.color, sprite.rect.center, int(sprite.size))
pygame.display.flip()
pygame.time.Clock().tick(30)
pygame.quit()
```
这段代码通过鼠标点击触发烟花的生成,在屏幕上呈现出绚丽多彩的新年烟火表演[^4]。
阅读全文