python放烟花代码
时间: 2023-09-23 17:07:41 浏览: 169
Python烟花秀代码
5星 · 资源好评率100%
以下是一个简单的 Python 放烟花代码,需要使用 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("放烟花啦!")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义烟花类
class Firework:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.explosion_radius = 0
self.explosion_speed = random.randint(1, 10)
def explode(self):
if self.explosion_radius < 100:
pygame.draw.circle(screen, self.color, (self.x, self.y), self.explosion_radius)
self.explosion_radius += self.explosion_speed
else:
fireworks.remove(self)
# 创建一个烟花列表
fireworks = []
# 循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 点击鼠标左键发射烟花
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
x, y = event.pos
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
fireworks.append(Firework(x, y, color))
# 更新烟花
for firework in fireworks:
firework.explode()
# 绘制背景
screen.fill(BLACK)
# 绘制烟花
for firework in fireworks:
pygame.draw.circle(screen, firework.color, (firework.x, firework.y), 5)
# 刷新屏幕
pygame.display.flip()
# 退出 Pygame
pygame.quit()
```
运行代码后,点击鼠标左键即可发射烟花。注意需要在 Pygame 环境下运行该代码。
阅读全文