基于Python实现烟花效果的示例代码

 更新时间:2022年06月13日 09:37:40   作者:m0_54850467  
这篇文章主要为大家详细介绍了如何利用Python制作出烟花的效果,文中的示例代码讲解详细,对我们学习Python有一定帮助,需要的可以参考一下

python烟花代码

如下

# -*- coding: utf-8 -*-

import math, random,time
import threading
import tkinter as tk
import re
#import uuid

Fireworks=[]
maxFireworks=8
height,width=600,600

class firework(object):
    def __init__(self,color,speed,width,height):
        #uid=uuid.uuid1()
        self.radius=random.randint(2,4)  #粒子半径为2~4像素
        self.color=color   #粒子颜色
        self.speed=speed  #speed是1.5-3.5秒
        self.status=0   #在烟花未爆炸的情况下,status=0;爆炸后,status>=1;当status>100时,烟花的生命期终止
        self.nParticle=random.randint(20,30)  #粒子数量
        self.center=[random.randint(0,width-1),random.randint(0,height-1)]   #烟花随机中心坐标
        self.oneParticle=[]    #原始粒子坐标(100%状态时)
        self.rotTheta=random.uniform(0,2*math.pi)  #椭圆平面旋转角

        #椭圆参数方程:x=a*cos(theta),y=b*sin(theta)
        #ellipsePara=[a,b]

        self.ellipsePara=[random.randint(30,40),random.randint(20,30)]   
        theta=2*math.pi/self.nParticle
        for i in range(self.nParticle):
            t=random.uniform(-1.0/16,1.0/16)  #产生一个 [-1/16,1/16) 的随机数
            x,y=self.ellipsePara[0]*math.cos(theta*i+t), self.ellipsePara[1]*math.sin(theta*i+t)    #椭圆参数方程
            xx,yy=x*math.cos(self.rotTheta)-y*math.sin(self.rotTheta),  y*math.cos(self.rotTheta)+x*math.sin(self.rotTheta)     #平面旋转方程
            self.oneParticle.append([xx,yy])
        
        self.curParticle=self.oneParticle[0:]     #当前粒子坐标
        self.thread=threading.Thread(target=self.extend)   #建立线程对象
        

    def extend(self):         #粒子群状态变化函数线程
        for i in range(100):
            self.status+=1    #更新状态标识
            self.curParticle=[[one[0]*self.status/100, one[1]*self.status/100] for one in self.oneParticle]   #更新粒子群坐标
            time.sleep(self.speed/50)
    
    def explode(self):
        self.thread.setDaemon(True)    #把现程设为守护线程
        self.thread.start()          #启动线程
            

    def __repr__(self):
        return ('color:{color}
'  
                'speed:{speed}
'
                'number of particle: {np}
'
                'center:[{cx} , {cy}]
'
                'ellipse:a={ea} , b={eb}
'
                'particle:
{p}
'
                ).format(color=self.color,speed=self.speed,np=self.nParticle,cx=self.center[0],cy=self.center[1],p=str(self.oneParticle),ea=self.ellipsePara[0],eb=self.ellipsePara[1])


def colorChange(fire):
    rgb=re.findall(r'(.{2})',fire.color[1:])
    cs=fire.status
    
    f=lambda x,c: hex(int(int(x,16)*(100-c)/30))[2:]    #当粒子寿命到70%时,颜色开始线性衰减
    if cs>70:
        ccr,ccg,ccb=f(rgb[0],cs),f(rgb[1],cs),f(rgb[2],cs)
    else:
        ccr,ccg,ccb=rgb[0],rgb[1],rgb[2]
        
    return '#{0:0>2}{1:0>2}{2:0>2}'.format(ccr,ccg,ccb)



def appendFirework(n=1):   #递归生成烟花对象
    if n>maxFireworks or len(Fireworks)>maxFireworks:
        pass
    elif n==1:
        cl='#{0:0>6}'.format(hex(int(random.randint(0,16777215)))[2:])   # 产生一个0~16777215(0xFFFFFF)的随机数,作为随机颜色
        a=firework(cl,random.uniform(1.5,3.5),width,height)
        Fireworks.append( {'particle':a,'points':[]} )   #建立粒子显示列表,‘particle'为一个烟花对象,‘points'为每一个粒子显示时的对象变量集
        a.explode()
    else:
        appendFirework()
        appendFirework(n-1)


def show(c):
    for p in Fireworks:                #每次刷新显示,先把已有的所以粒子全部删除
        for pp in p['points']:
            c.delete(pp)
    
    for p in Fireworks:                #根据每个烟花对象,计算其中每个粒子的显示对象
        oneP=p['particle']
        if oneP.status==100:        #状态标识为100,说明烟花寿命结束
            Fireworks.remove(p)     #移出当前烟花
            appendFirework()           #新增一个烟花
            continue
        else:
            li=[[int(cp[0]*2)+oneP.center[0],int(cp[1]*2)+oneP.center[1]] for cp in oneP.curParticle]       #把中心为原点的椭圆平移到随机圆心坐标上
            color=colorChange(oneP)   #根据烟花当前状态计算当前颜色
            for pp in li:
                p['points'].append(c.create_oval(pp[0]-oneP.radius,  pp[1]-oneP.radius,  pp[0]+oneP.radius,  pp[1]+oneP.radius,  fill=color))  #绘制烟花每个粒子

    root.after(50, show,c)  #回调,每50ms刷新一次

if __name__=='__main__':
    appendFirework(maxFireworks)
    
    root = tk.Tk()
    cv = tk.Canvas(root, height=height, width=width)
    cv.create_rectangle(0, 0, width, height, fill="black")

    cv.pack()

    root.after(50, show,cv)
    root.mainloop()

图片展示

到此这篇关于基于Python实现烟花效果的示例代码的文章就介绍到这了,更多相关Python烟花内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 简单实例带你了解Python的编译和执行全过程

    简单实例带你了解Python的编译和执行全过程

    python 是一种解释型的编程语言,所以不像编译型语言那样需要显式的编译过程。然而,在 Python 代码执行之前,它需要被解释器转换成字节码,这个过程就是 Python 的编译过程,还不知道的朋友快来看看吧
    2023-04-04
  • python的函数形参和返回值你了解吗

    python的函数形参和返回值你了解吗

    这篇文章主要为大家详细介绍了python的函数形参和返回值,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-03-03
  • python pyinstaller打包exe报错的解决方法

    python pyinstaller打包exe报错的解决方法

    这篇文章主要给大家介绍了关于python pyinstaller打包exe报错的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者使用python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-11-11
  • Python数据结构之单链表详解

    Python数据结构之单链表详解

    这篇文章主要为大家详细介绍了Python数据结构之单链表的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-09-09
  • 深入探讨Python中的RegEx模式匹配

    深入探讨Python中的RegEx模式匹配

    正则表达式通常缩写为 regex,是处理文本的有效工具,这篇文章主要来和大家深入探讨一下Python中的RegEx模式匹配,感兴趣的可以了解一下
    2023-07-07
  • Python入门教程(三十六)Python的文件写入

    Python入门教程(三十六)Python的文件写入

    这篇文章主要介绍了Python入门教程(三十六)Python的文件写入,open()函数可以打开一个文件供读取或写入,如果这个函数执行成功,会回传文件对象,需要的朋友可以参考下
    2023-05-05
  • Python中的urllib库高级用法教程

    Python中的urllib库高级用法教程

    这篇文章主要介绍了Python中的urllib库高级用法教程,想要请求需要设置一些请求头,如果要在请求的时候增加一些请求头,那么就必须使用request.Request类来实现了,比如要增加一个 User-Agent ,增加一个 Referer 头信息等,需要的朋友可以参考下
    2023-10-10
  • python中有函数重载吗

    python中有函数重载吗

    在本篇内容里下边给大家整理的是关于python函数重载的知识点总结,有需要的朋友们可以学习下。
    2020-05-05
  • Pytorch 多维数组运算过程的索引处理方式

    Pytorch 多维数组运算过程的索引处理方式

    今天小编就为大家分享一篇Pytorch 多维数组运算过程的索引处理方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • Python 类属性与实例属性,类对象与实例对象用法分析

    Python 类属性与实例属性,类对象与实例对象用法分析

    这篇文章主要介绍了Python 类属性与实例属性,类对象与实例对象用法,结合实例形式分析了java类相关的属性、实例化、对象等相关概念与操作技巧,需要的朋友可以参考下
    2019-09-09

最新评论