python生日快乐烟花动画代码
时间: 2024-10-11 22:14:43 浏览: 134
python烟花代码直接用
5星 · 资源好评率100%
在Python中制作生日快乐烟花动画,可以使用`pygame`库来创建图形和控制动画。下面是一个简单的示例代码,它会在屏幕上绘制出烟花效果,并循环播放“Happy Birthday”祝福语:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Happy Birthday Fireworks")
# 定义颜色
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
firework_colors = [random.choice(colors) for _ in range(20)]
# 烟花位置和速度
fireworks = []
for i in range(10):
fireworks.append((random.randint(0, screen.get_width()), random.randint(0, screen.get_height()), 0, 10))
font = pygame.font.SysFont(None, 36)
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 清除屏幕
screen.fill((0, 0, 0))
# 绘制烟花
for firework in fireworks:
x, y, speed, size = firework
size += speed
pygame.draw.circle(screen, firework_colors.pop(), (x, y), size)
# 当烟花达到一定大小时消失并随机生成新的烟花
if size > 100:
fireworks.remove(firework)
new_firework = (random.randint(0, screen.get_width()), random.randint(0, screen.get_height()), -speed / 2, 10)
fireworks.append(new_firework)
# 显示文字祝福
text = font.render('Happy Birthday', True, (255, 255, 255))
screen.blit(text, (0, 0))
# 更新屏幕
pygame.display.flip()
```
阅读全文