Python implements circle fireworks_With complete source code [Part 21 - Python New Year]

Preface

Fireworks are a common beautiful expression in celebrations, celebrations or celebrations. They bring joy and surprise to people with their colorful lights and dazzling shapes. In this project, we will use the Python programming language to create a simple and interesting program that draws the effect of circular fireworks on the screen.

  • Use Python's graphics library (such as pygame, turtle, etc.) to draw the effect of circular fireworks on the screen.
  • Realize the dynamic effect of fireworks so that they appear on the screen in a lively way.
  • Consider adding some additional special effects, such as color changes after fireworks explode, trail effects, etc., to enhance the visual impact.

Implementation steps:

  • Import the required graphics library (e.g. pygame).
  • Initialize the screen and set the window size.
  • Design a function to draw the circular effect of fireworks.
  • In the main program, call the function that draws fireworks and display the fireworks effect on the screen.
  • Consider adding dynamic effects of fireworks, such as the process of fireworks rising, exploding, etc.
  • Optimize the program and add some additional special effects to improve the beauty of the fireworks.

Rendering (dynamic)

Insert image description here
Insert image description here

Complete code

# -*- 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}\n'  
                'speed:{speed}\n'
                'number of particle: {np}\n'
                'center:[{cx} , {cy}]\n'
                'ellipse:a={ea} , b={eb}\n'
                'particle:\n{p}\n'
                ).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()
import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置窗口大小
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Circle Fireworks")

# 定义烟花绘制函数
def draw_firework(x, y, color):
    pygame.draw.circle(screen, color, (x, y), 10)

# 主程序
def main():
    clock = pygame.time.Clock()

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

        # 清空屏幕
        screen.fill((0, 0, 0))

        # 生成随机位置和颜色的烟花
        firework_x = random.randint(50, screen_width - 50)
        firework_y = random.randint(50, screen_height - 50)
        firework_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

        # 绘制烟花
        draw_firework(firework_x, firework_y, firework_color)

        # 更新显示
        pygame.display.flip()

        # 控制帧率
        clock.tick(30)

if __name__ == "__main__":
    main()

Code explanation

This code implements a simple firework animation effect, using the Python tkinterlibrary to display the graphical interface. The following is the main analysis of the code:

  1. Import module:

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

    The required modules are imported, including mathematical calculations, random number generation, threads, graphical interfaces, regular expressions, etc.

  2. Global variable definition:

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

    Global variables are defined, including the fireworks list, the maximum number of fireworks, and the height and width of the canvas.

  3. Fireworks fireworkdefinition:

    class firework(object):
        # ... (详细的初始化和方法定义在这里)
    

    The Fireworks class is defined, including Fireworks initialization, state change thread ( extend), explosion method ( explode) and __repr__methods for string representation of objects.

  4. Color change function colorChange:

    def colorChange(fire):
        # ... (根据粒子状态计算颜色)
    

    The color is calculated based on the particle state. When the particle life reaches 70%, the color begins to decay linearly.

  5. Fireworks generation function appendFirework:

    def appendFirework(n=1):
        # ... (递归生成烟花对象的函数)
    

    Recursively generate fireworks objects, which include setting the color, speed, initial coordinates and other information of the fireworks, and starting the explosion thread of the fireworks.

  6. Show function show:

    def show(c):
        # ... (每次刷新画布,绘制烟花粒子)
    

    Each time the canvas is refreshed, firework particles are drawn, including updating firework status, color, and position information.

  7. Main program entry:

    if __name__=='__main__':
        # ... (初始化烟花,创建tkinter窗口并启动刷新循环)
    

    Initialize Fireworks, create tkinterthe window, start a refresh loop, and refresh the canvas every 50 milliseconds.

Overall, this code tkintercreates a simple window, and then displays the effects of multiple fireworks in the window, and implements the animation effect of fireworks through threads and timers.

Summarize

This code implements a simple but interesting firework animation effect, combining the knowledge of multi-threading and graphical interface programming. The following are some summaries and thoughts:

  1. Multi-threaded application: By using the module in Python threading, the state changes (methods) and animation effects of fireworks particles are realized extend. This method enables the program to perform multiple tasks at the same time, improving the responsiveness and concurrency of the program.

  2. Graphical interface programming: Use to tkintercreate a simple window and Canvasrealize animation display through canvas. This method allows the program to display fireworks effects in the graphical interface, increasing the user's visual experience.

  3. Mathematical and physical model: The particle coordinates of the fireworks were created by using elliptical parametric equations and plane rotation equations in mathematics. This mathematical model makes the trajectory of fireworks more realistic and interesting.

  4. Control of animation effects: By controlling the state and color of particles, the life cycle and color change effects of fireworks are realized. This design makes the performance of fireworks more vivid and diverse.

  5. Use of recursion: Firework objects are generated recursively, allowing multiple fireworks to be displayed at the same time. This way of recursively generating objects makes the program structure clear and facilitates the management and expansion of fireworks.

Overall, this project not only demonstrates the application of Python in graphical interface programming and multi-threading, but also fully reflects the use of mathematical and physical models in programming. Through this project, you can gain a deeper understanding of multi-threaded programming, graphical interface design, and the application of mathematical models in computer graphics.

Message

In the journey of learning and programming, it is very important to constantly challenge yourself and explore new areas. Remember, every line of code is an opportunity to learn, and every bug is an opportunity to grow. Stay curious, stay thirsty for knowledge, and always have a learning mindset.

No matter what kind of difficulties and challenges you face, believe in your own abilities and believe that persistent efforts will eventually lead to success. At the same time, cooperating with others, sharing experiences, and making progress together are an integral part of the team.

Programming is an art, and creativity is its soul. Be brave enough to create and try, and let your code become a way of expression to convey your thoughts and passion. Most importantly, enjoy the process of programming and enjoy solving problems.

May your code change the world, may your path of exploration become wider and wider, and may each of your projects be full of creativity and achievement. Come on, the future is bright!
Insert image description here

Guess you like

Origin blog.csdn.net/weixin_52908342/article/details/135424881