pygame 烟花效果

# 初始化

pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('烟花效果')

# 焰火发射

particles = []  # 焰火粒子
def firework(x, y):
    num_particles = 100  # 每次发射的粒子数量
    for _ in range(num_particles):
        direction = random.uniform(0, 2 * math.pi)  # 随机方向
        speed = random.uniform(2, 6)  # 随机速度
        particles.append({
            'x': x,
            'y': y,
            'vx': math.cos(direction) * speed,
            'vy': math.sin(direction) * speed,
            'color': colorlib.randcolorTuple(),
            'size': random.uniform(1, 4),  # 粒子的初始大小
            'life': random.uniform(100, 200)  # 粒子的生命周期
        })

# 更新屏幕

def update_screen():
    global particles
    screen.fill((0, 0, 0))  # 填充黑色背景
    for particle in particles[:]:
        particle['x'] += particle['vx']
        particle['y'] += particle['vy']
        particle['life'] -= 5
        coordinate = particle['x'], particle['y']
        radius = particle['size'] * particle['life'] / 100.0
        pygame.draw.circle(screen, particle['color'], coordinate, radius)
        if particle['life'] <= 0 or particle['y'] > screen_height:
            particles.remove(particle)

# 主循环

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    # 每隔一段时间发射一次烟花
    if random.randint(0, 2)==0:  # 发射随机时间
        firework(random.randint(0, screen_width), random.randint(0, screen_height//3*2))

    update_screen()
    pygame.display.flip()  # 更新整个屏幕
    pygame.time.Clock().tick(60)  # 控制帧率

pygame 烟花效果

完整代码

其中,库colorlib来源于: python 教你如何创建一个自定义库 colorlib.py-CSDN博客

import pygame
import random
import math
import colorlib

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption('烟花效果')

# 焰火粒子
particles = []

# 焰火发射
def firework(x, y):
    num_particles = 100  # 每次发射的粒子数量
    for _ in range(num_particles):
        direction = random.uniform(0, 2 * math.pi)  # 随机方向
        speed = random.uniform(2, 6)  # 随机速度
        particles.append({
            'x': x,
            'y': y,
            'vx': math.cos(direction) * speed,
            'vy': math.sin(direction) * speed,
            'color': colorlib.randcolorTuple(),
            'size': random.uniform(1, 4),  # 粒子的初始大小
            'life': random.uniform(100, 200)  # 粒子的生命周期
        })

# 更新屏幕
def update_screen():
    global particles
    screen.fill((0, 0, 0))  # 填充黑色背景
    for particle in particles[:]:
        particle['x'] += particle['vx']
        particle['y'] += particle['vy']
        particle['life'] -= 5
        coordinate = particle['x'], particle['y']
        radius = particle['size'] * particle['life'] / 100.0
        pygame.draw.circle(screen, particle['color'], coordinate, radius)
        if particle['life'] <= 0 or particle['y'] > screen_height:
            particles.remove(particle)

# 主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    # 每隔一段时间发射一次烟花
    if random.randint(0, 2)==0:  # 发射随机时间
        firework(random.randint(0, screen_width), random.randint(0, screen_height//3*2))

    update_screen()
    pygame.display.flip()  # 更新整个屏幕
    pygame.time.Clock().tick(60)  # 控制帧率

优化代码

把粒子的字典描述方式改为类:

       {    'x': x,
            'y': y,
            'vx': math.cos(direction) * speed,
            'vy': math.sin(direction) * speed,
            'color': colorlib.randcolorTuple(),
            'size': random.uniform(1, 4),  # 粒子的初始大小
            'life': random.uniform(100, 200)  # 粒子的生命周期
        } 

修改成:

class Firework:
    def __init__(self, x=0, y=0):
        self.x, self.y = self.xy = x, y
        direction = random.uniform(0, 2 * math.pi)  # 随机方向
        speed = random.uniform(2, 6)  # 随机速度
        self.vx = math.cos(direction) * speed
        self.vy = math.sin(direction) * speed
        self.color = tuple(random.randint(30, 255) for _ in range(3))
        self.size = random.uniform(2, 4)  # 粒子的初始大小
        self.life = random.uniform(100, 200)  # 粒子的生命周期

随机颜色也修改一下,最后优化好的完整代码如下:

import pygame, random, math

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption('烟花效果')

class Firework:
    def __init__(self, x=0, y=0):
        self.x, self.y = self.xy = x, y
        direction = random.uniform(0, 2 * math.pi)  # 随机方向
        speed = random.uniform(2, 6)  # 随机速度
        self.vx = math.cos(direction) * speed
        self.vy = math.sin(direction) * speed
        self.color = tuple(random.randint(30, 255) for _ in range(3))
        self.size = random.uniform(2, 4)  # 粒子的初始大小
        self.life = random.uniform(100, 200)  # 粒子的生命周期
    def update(self):
        self.x += self.vx
        self.y += self.vy
        self.life -= 5

# 焰火粒子列表
particles = []

# 更新屏幕
def update_screen():
    global particles
    screen.fill((0, 0, 0))  # 填充黑色背景
    # 遍历并更新粒子
    for particle in particles[:]:
        particle.update()
        radius = particle.size * particle.life // 100  # 计算半径
        pygame.draw.circle(screen, particle.color, (particle.x, particle.y), radius)
        # 如粒子生命周期结束或飞出屏幕,就删除
        if not (particle.life>0 and 0<particle.x<screen_width and 0<particle.y<screen_height):
            particles.remove(particle)
    pygame.display.flip()  # 更新整个屏幕

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # 每隔一段时间发射一次烟花
    if random.randint(0, 3) == 0:  # 发射随机时间
        xy = random.randint(0, screen_width), random.randint(0, screen_height*2//3)
        particles.extend(Firework(*xy) for _ in range(100))
    update_screen()
    pygame.display.flip()  # 更新整个屏幕
    pygame.time.Clock().tick(60)  # 控制帧率

pygame.quit()

相关推荐

  1. 用canvas整个烟花效果

    2024-04-23 01:08:03       7 阅读
  2. Go实现一个简单的烟花效果(附带源码)

    2024-04-23 01:08:03       46 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-23 01:08:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-23 01:08:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-23 01:08:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-23 01:08:03       20 阅读

热门阅读

  1. git工具的安装及使用

    2024-04-23 01:08:03       12 阅读
  2. backtracking Leetcode 回溯算法题

    2024-04-23 01:08:03       12 阅读
  3. Linux文本处理三剑客:awk、grep和sed

    2024-04-23 01:08:03       15 阅读
  4. js高级 笔记03

    2024-04-23 01:08:03       11 阅读
  5. FastJson的使用

    2024-04-23 01:08:03       13 阅读
  6. 【程序设计与算法——C/C++入门】C语言入门

    2024-04-23 01:08:03       17 阅读
  7. 37-4 用Python编写SQL注入的基于错误报告的POC

    2024-04-23 01:08:03       14 阅读
  8. 12.Vue2.x收集表单数据input | v-model | select

    2024-04-23 01:08:03       13 阅读