python代码画动态烟花
时间: 2024-01-10 19:04:55 浏览: 229
以下是使用Python绘制动态烟花的代码示例:
```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("Fireworks")
# 定义烟花类
class Firework:
def __init__(self):
self.x = random.randint(0, screen_width)
self.y = screen_height
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.speed = random.randint(1, 5)
self.radius = random.randint(2, 6)
def move(self):
self.y -= self.speed
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, int(self.y)), self.radius)
# 创建烟花列表
fireworks = []
# 游戏主循环
running = True
while running:
# 填充背景色
screen.fill((0, 0, 0))
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
# 按下1生成一个新的烟花
if event.key == pygame.K_1:
fireworks.append(Firework())
# 按下2生成10个烟花
if event.key == pygame.K_2:
for i in range(10):
fireworks.append(Firework())
# 更新烟花位置并绘制
for firework in fireworks:
firework.move()
firework.draw()
# 更新屏幕显示
pygame.display.flip()
# 退出游戏
pygame.quit()
```
阅读全文