python写一段烟花代码
时间: 2023-07-10 20:34:34 浏览: 43
下面是一个简单的烟花代码,使用 Python 的 Pygame 库实现:
```python
import pygame
import random
pygame.init()
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Fireworks")
clock = pygame.time.Clock()
fireworks = []
for i in range(10):
x = random.randint(100, WIDTH - 100)
y = random.randint(100, HEIGHT - 100)
size = random.randint(5, 15)
fireworks.append({"x": x, "y": y, "size": size, "color": (255, 255, 255), "speed": random.randint(1, 3)})
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill((0, 0, 0))
for firework in fireworks:
pygame.draw.circle(screen, firework["color"], (firework["x"], firework["y"]), firework["size"])
firework["y"] -= firework["speed"]
if firework["y"] < 0:
fireworks.remove(firework)
x = random.randint(100, WIDTH - 100)
y = random.randint(100, HEIGHT - 100)
size = random.randint(5, 15)
fireworks.append({"x": x, "y": y, "size": size, "color": (255, 255, 255), "speed": random.randint(1, 3)})
pygame.display.update()
clock.tick(60)
```
这段代码会在屏幕上生成 10 个白色的烟花,随机分布在屏幕上的位置,然后向上移动,直到消失。当一个烟花消失时,会生成一个新的烟花,来保持烟花的数量不变。你可以根据自己的需要调整烟花的数量、颜色、大小、速度等参数。