用Python生成一个烟花代码
时间: 2024-04-20 17:06:31 浏览: 115
以下是一个用Python生成烟花的示例代码,需要使用`pygame`库。
```python
import pygame
import random
pygame.init()
# 设置窗口尺寸
win = pygame.display.set_mode((800, 600))
# 设置烟花颜色
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(100, 700)
self.y = 550
self.explode = False
self.color = random.choice(colors)
self.radius = 3
def draw(self):
if not self.explode:
pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)
else:
for i in range(30):
dx = random.randint(-10, 10)
dy = random.randint(-10, 10)
pygame.draw.circle(win, self.color, (self.x + dx, self.y + dy), self.radius)
def move(self):
if not self.explode:
self.y -= random.randint(3, 5)
if self.y <= 150:
self.explode = True
else:
self.radius += 1
if self.radius >= 30:
self.__init__()
# 定义主函数
def main():
fireworks = []
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
win.fill((0, 0, 0))
# 生成烟花
if random.random() < 0.1:
fireworks.append(Firework())
# 绘制烟花
for firework in fireworks:
firework.draw()
firework.move()
# 移除已经爆炸的烟花
fireworks = [f for f in fireworks if not f.explode or f.radius <= 30]
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
main()
```
运行代码后,将会看到一个黑色窗口,不断出现随机颜色的烟花,直到程序关闭。
阅读全文