python粒子烟花代码
时间: 2023-12-10 12:35:55 浏览: 134
以下是一个简单的Python粒子烟花代码,使用了Pygame和random库。代码中定义了一个Firework类,用于创建烟花对象,以及一个Particle类,用于创建烟花中的粒子对象。在主循环中,检测键盘事件,按下1键时创建一个新的烟花,按下2键时创建10个烟花。每个烟花都会在屏幕上随机生成,并且会发射出一些粒子,粒子的颜色和速度也是随机的。
```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("Particle Fireworks")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义Firework类
class Firework:
def __init__(self):
self.x = random.randint(0, screen_width)
self.y = random.randint(0, screen_height // 2)
self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
self.exploded = False
self.particles = []
def explode(self):
self.exploded = True
for i in range(100):
self.particles.append(Particle(self.x, self.y, self.color))
def update(self):
if not self.exploded:
self.y -= 5
if self.y <= 200:
self.explode()
for particle in self.particles:
particle.update()
def draw(self):
if not self.exploded:
pygame.draw.circle(screen, self.color, (self.x, self.y), 5)
for particle in self.particles:
particle.draw()
# 定义Particle类
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.speed = random.randint(1, 5)
self.angle = random.uniform(0, 2 * 3.14)
def update(self):
self.x += int(self.speed * 2 * 3.14 * math.cos(self.angle))
self.y += int(self.speed * 2 * 3.14 * math.sin(self.angle))
self.speed -= 0.1
if self.speed <= 0:
self.speed = 0
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), 2)
# 创建烟花列表
fireworks = []
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
fireworks.append(Firework())
if event.key == pygame.K_2:
for i in range(10):
fireworks.append(Firework())
# 更新和绘制烟花
screen.fill(BLACK)
for firework in fireworks:
firework.update()
firework.draw()
# 更新屏幕
pygame.display.flip()
# 退出Pygame
pygame.quit()
```
阅读全文