Every day knock code friends, have you ever thought that the code can also become cool and romantic? Today we will teach you to use Python to simulate the bloom of fireworks to celebrate the French team last night, outside the work can be at any time to let the program to put a fireworks show.
This interesting little project is not complicated, just a little bit of visualization skills, more than 100 lines of Python code and library Tkinter, and finally we can achieve the following effect:
After completing this tutorial, you can also make such a fireworks show.
Holistic Grooming Concepts
Our whole concept is relatively simple.
As shown, here we simulate the explosion by splitting a particle on the screen into an X number of particles. Particles can "swell", meaning they move at a constant speed and are equal in angle to each other. This will allow us to simulate the display of fireworks in an outward-expanding circle. After a certain period of time, the particles will enter the "Free Fall" phase, which is due to the gravity factor they start falling to the ground, like the fireworks extinguished after the bloom.
Designing fireworks with Python and tkinter: basic knowledge
There is no longer a brain to throw out all the math knowledge, we write the code side to say the theory. First, make sure you install and import the Tkinter, which is the standard GUI library for Python and is widely used in a wide variety of project and program development, and using Tkinter in Python can quickly create GUI applications.
import tkinter as tkfrom PIL import Image, ImageTkfrom time import time, sleepfrom random import choice, uniform, randintfrom math import sin, cos, radians复制代码
In addition to Tkinter, in order to have a nice background for the interface, we also import PIL for image processing, as well as importing other packages, such as time,random and math. They make it easier for us to control the trajectory of the fireworks particles.
The basic settings for the Tkinter application are as follows:
root = tk.Tk()复制代码
In order to initialize the Tkinter, we must create a TK () root widget (root widget), which is a window with a title bar and other decorations provided by the window manager. The root component must be created before we create other widgets, and there can be only one root part.
w = tk.Label(root, text="Hello Tkinter!")复制代码
This line of code contains the label part. The first parameter in the label call is the name of the parent window, which is the "root" we use here. The keyword parameter "text" indicates what text is displayed. You can also call other widgets: Button,canvas and so on.
w.pack()root.mainloop()复制代码
The next two lines of code are important. The packing method here is to tell Tkinter to resize the window to fit the widget. The window will not appear until we enter the Tkinter event loop, which is called by Root.mainloop (). The script will remain in the event loop until we close the window.
Translate fireworks into code
Now we design an object that represents each particle in the fireworks event. Each particle has some important properties that govern its appearance and movement: size, color, position, speed, and so on.
‘‘' Generic class for particlesparticles is emitted almost randomly on the sky, forming a round of circle (a star) before FA Lling and getting Removedfrom canvasattributes:-Id:identifier of a particular particle in a star-x, Y:x,y-coor Dinate of a star (point of explosion)-VX, vy:speed of particle in X, y coordinate-total:total number of partic Le in a star-age:how long have the particle last on Canvas-color:self-explantory-cv:canvas-lifespan: How long a particle would last over canvas-intial_speed:speed of particle at explosion '' class Part:def __init__ (self, CV, idx, Total, Explosion_speed, x=0., y=0., VX = 0., vy = 0., size=2., color =
' red ', lifespan = 2, **kwargs): self.id = idx self.x = x self.y = y Self.initial_speed = exp Losion_speed SELF.VX = VX Self.vy = vy Self.total = Total Self.age = 0 Self.color = Col or SELF.CV = CV self.cid = self.cv.create_oval (X-size, y-size, x + size, y + size , fill=self.color) Self.lifespan = lifespan
Copy code
If we go back and think about the initial idea, we will realize that we must ensure that all the particles that bloom in each firework must go through 3 different stages: "Swell" "Fall" and "disappear". So let's add some more motion functions to the particle class as follows:
def update (self, DT):# particle expansion if self.alive () and Self.expand (): move_x = cos (rad Ians (self.id*360/self.total)) *self.initial_speed move_y = sin (radians (self.id*360/self.total)) *self.initial_speed SELF.VX = move_x/(float (DT) *1000) Self.vy = move_y/( float (DT) *1000) self.cv.move (Self.cid, move_x, move_y) # fall in freefall elif self.alive (): move_x = cos (radians (self.id*360/self.total)) # we technically Don ' t need to update x, y because move would do the job Self.cv.move (self.cid, SELF.VX + move_x, SELF.VY+GRAVITY*DT) self.v Y + = Gravity*dt # if the life cycle of the particle has been past, remove it elif self.cid is not None: Cv.delete (self.cid) self.cid = None copy code
Of course, it also means that we have to define how long each particle will bloom and how long it will fall. This part requires us to try a few more parameters to achieve the best visual effect.
# 定义膨胀效果的时间帧def expand (self): return self.age <= 1.2# 检查粒子是否仍在生命周期内def alive(self): return self.age <= self.lifespan复制代码
Using Tkinter Simulation
Now we conceptualize the movement of particles, but it is clear that a firework cannot have only one particle, and a firework show cannot have only one firework. Our next step is for Python and tkinter to "emit" particles in a controlled way to the heavens.
Here we need to upgrade from manipulating a particle to displaying multiple fireworks on the screen and multiple particles in each firework.
Our approach is as follows: Create a list of columns, each of which is a firework containing a column of particles. Examples in each list have the same x, y coordinates, size, color, and initial speed.
numb_explode = randint(6,10)# 为所有模拟烟花绽放的全部粒子创建一列列表for point in range(numb_explode): objects = [] x_cordi = randint(50,550) y_cordi = randint(50, 150) size = uniform (0.5,3) color = choice(colors) explosion_speed = uniform(0.2, 1) total_particles = randint(10,50) for i in range(1,total_particles): r = part(cv, idx = i, total = total_particles, explosion_speed = explosion_speed, x = x_cordi, y = y_cordi, color=color, size = size, lifespan = uniform(0.6,1.75)) objects.append(r)explode_points.append(objects)复制代码
Our next step is to ensure that the properties of the particles are updated periodically. Here we set the particles to update their state every 0.01 seconds, stopping the update after 1.8 seconds (which means that each particle has a time of 1.6 seconds, where 1.2 seconds is the "Bloom" state, 0.4 seconds is the "fall" state, and 0.2 seconds is in the edge state before tkinter it completely removed).
total_time = .0# 在1.8秒时间帧内保持更新while total_time < 1.8: sleep(0.01) tnew = time() t, dt = tnew, tnew - t for point in explode_points: for part in point: part.update(dt) cv.update() total_time += dt复制代码
Now, we just need to merge the last two gist into a function that can be called by Tkinter, call it simulate (). This function will show all the data items and update the properties of each data item according to the time we set. In our main code, we call this function with a alarm processing module after (), and after () waits for a certain amount of time before calling the function. We set here to let Tkinter wait 100 units (1 seconds) to re-tune simulate.
if __name__ == ‘__main__‘: root = tk.Tk() cv = tk.Canvas(root, height=600, width=600) # 绘制一个黑色背景 cv.create_rectangle(0, 0, 600, 600, fill="black") cv.pack() root.protocol("WM_DELETE_WINDOW", close) # 在1秒后才开始调用stimulate() root.after(100, simulate, cv) root.mainloop()复制代码
Okay, so we're going to put a fireworks show in Python code:
This article is just the basic version, after you are further familiar with Tkinter, you can add more beautiful background photos, so that the code for you to bloom more beautiful fireworks!
I have a public number, and I often share some of the stuff about Python technology. If you like my share, you can use the search "Python language learning" to follow
Welcome to join thousands of people to exchange questions and answers skirt: 699+749+852
Celebrating France's title: Putting a fireworks show in Python