来个python烟花代码
时间: 2024-11-14 18:13:54 浏览: 2
当然可以,Python中的烟花效果通常通过动画库如`pygame`或`PIL`来实现,这里是一个简单的例子,使用`pygame`来模拟烟花效果:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("简单烟花")
# 烟花颜色和速度
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
speeds = [random.randint(2, 5) for _ in range(len(colors))]
def draw_firework(x, y, color, speed):
size = 10
while True:
pygame.draw.circle(screen, color, (x, y), size)
x += speed
if x > screen_width or x < 0:
break
size -= 1
if size <= 0:
break
pygame.display.flip()
pygame.time.delay(10)
# 主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 创建随机位置和颜色的烟花
fireworks = [(random.randint(0, screen_width), random.randint(0, screen_height)) for _ in range(random.randint(5, 10))]
for firework in fireworks:
draw_firework(firework[0], firework[1], colors[random.randint(0, len(colors) - 1)], speeds[random.randint(0, len(speeds) - 1)])
# 游戏结束清理
pygame.quit()
```
这个代码会创建一些随机位置和颜色的“烟花”在屏幕上爆炸,并随着时间逐渐消失。运行此代码需要安装Pygame模块,如果你还没安装,可以使用`pip install pygame`命令。
阅读全文