pygame 烟花效果

简介: 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()

目录
相关文章
|
11月前
|
Java 图形学 Python
用Python和Pygame打造绚丽烟花效果+节日祝福语
本文介绍了一款基于Python和Pygame库实现的烟花效果程序,模拟烟花发射、爆炸及粒子轨迹,结合动态文本显示祝福语,营造逼真的节日氛围。程序包括烟花类、粒子类、痕迹类和动态文本显示功能,通过随机化颜色、速度和粒子数量增加效果多样性。用户可以看到烟花从屏幕底部发射、上升并在空中爆炸,伴随粒子轨迹和动态祝福语“蛇年大吉”、“Happy Spring Festival”。文章详细解析了核心代码逻辑和技术要点,帮助读者理解如何利用Pygame库实现复杂视觉效果,并提供了未来改进方向,如优化性能、增加特效和增强交互性。
613 20
用Python和Pygame打造绚丽烟花效果+节日祝福语
|
存储 人工智能 算法
使用 Python 和 Pygame 制作游戏:第九章到第十章
使用 Python 和 Pygame 制作游戏:第九章到第十章
333 0
使用 Python 和 Pygame 制作游戏:第九章到第十章
|
Python
Python使用pygame播放MP3
Python使用pygame播放MP3
206 0
|
定位技术 Python
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
2580 1
|
JSON 开发工具 git
基于Python和pygame的植物大战僵尸游戏设计源码
本项目是基于Python和pygame开发的植物大战僵尸游戏,包含125个文件,如PNG图像、Python源码等,提供丰富的游戏开发学习素材。游戏设计源码可从提供的链接下载。关键词:Python游戏开发、pygame、植物大战僵尸、源码分享。
|
开发框架 Python
Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。
【6月更文挑战第21天】Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。要开始,先通过`pip install pygame`安装。基本流程包括:初始化窗口、处理事件循环、添加游戏元素(如玩家和敌人)、响应用户输入、更新游戏状态及结束条件。随着项目发展,可逐步增加复杂性。
474 1
|
Linux 开发工具 开发者
Pygame是一个免费且开源的Python库
【6月更文挑战第12天】Pygame是一个免费且开源的Python库
507 3
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
|
索引 Python
技术好文共享:用Python的Pygame包做飞行棋
技术好文共享:用Python的Pygame包做飞行棋

热门文章

最新文章