python cool fireworks confession source code
Friends who type code every day, have you ever thought that code can also become cool and romantic? Today I will teach you how to use Python to simulate blooming fireworks. You can also let the program set off a fireworks show for you at any time after work.
python cool fireworks expression source code
This interesting little project is not complicated, just a little visualization skills, 100 With just a few lines of Python code and the program library Tkinter, we can finally achieve the following effect:
After completing this tutorial, you can also create such a fireworks show.
Overall concept review
Our entire concept is relatively simple.
As shown in the picture above, we simulate the explosion effect by splitting a particle on the screen into X number of particles. The particles "expand," meaning they move at a constant speed and at equal angles to each other. This will allow us to simulate a fireworks display in the form of an expanding circle. After a certain amount of time, the particles enter a "free fall" phase, where they begin to fall to the ground due to gravity, like fireworks that bloom and then go out.
(Recommended learning: Programming learning course)
Basic knowledge: Designing fireworks with Python and Tkinter
No more here Throw out all the mathematical knowledge at once, and we talk about theory while writing code. First, make sure you install and import Tkinter, which is Python's standard GUI library and is widely used in a variety of projects and program development. Using Tkinter in Python can quickly create GUI applications.
import tkinter as tk from PIL import Image, ImageTk from time import time, sleep from random import choice, uniform, randint from math import sin, cos, radians
In addition to Tkinter, in order to make the interface have a beautiful background, we also import PIL for image processing, as well as other packages, such as time, random and math. They allow us to more easily control the trajectory of fireworks particles.
The basic settings of the Tkinter application are as follows:
root = tk.Tk()
In order to initialize Tkinter, we must create a Tk() root widget, which is a window with a title bar and a Other decorations provided by the window manager. This root widget must be created before we create other widgets, and there can only be one root widget.
w = tk.Label(root, text="Hello Tkinter!")
This line of code contains the Label component. The first parameter in the Label call is the name of the parent window, which is the "root" we use here. The keyword argument "text" specifies the text content to be displayed. You can also call other widgets: Button, Canvas, etc.
w.pack() root.mainloop()
The next two lines of code are important. The packaging method here is to tell Tkinter to resize the window to fit the widget used. The window will not appear until we enter the Tkinter event loop and is called by root.mainloop(). The script will stay in the event loop until we close the window.
Translate fireworks blooming into code
Now we design an object to represent each particle in the fireworks event. Each particle has some important properties that govern its appearance and movement: size, color, position, speed, etc.
''' particles 类 粒子在空中随机生成随机,变成一个圈、下坠、消失 属性: - id: 粒子的id - x, y: 粒子的坐标 - vx, vy: 在坐标的变化速度 - total: 总数 - age: 粒子存在的时长 - color: 颜色 - cv: 画布 - lifespan: 最高存在时长 ''' 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 = explosion_speed self.vx = vx self.vy = vy self.total = total self.age = 0self.color = color self.cv = cv self.cid = self.cv.create_oval( x - size, y - size, x + size, y + size, fill=self.color) self.lifespan = lifespan
If we think back to the original idea, we will realize that it is necessary to ensure that all particles of each firework must go through 3 different stages, namely "expansion", "fall" and "disappearance" . So we add some more motion functions to the particle class, as shown below:
def update(self, dt): # 粒子膨胀if self.alive() and self.expand(): move_x = cos(radians(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) # 以自由落体坠落 elif self.alive(): move_x = cos(radians(self.id*360/self.total)) # we technically don't need to update x, y because move will do the job self.cv.move(self.cid, self.vx + move_x, self.vy+GRAVITY*dt) self.vy += GRAVITY*dt # 如果粒子的生命周期已过,就将其移除 elif self.cid is not None: cv.delete(self.cid) self.cid = None
Of course, this also means that we must define how long each particle blooms and how long it falls. This part requires us to try some 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 obvious that a firework cannot have only one particle, and a firework show cannot have only one firework. . Our next step is to let Python and Tkinter continuously "fire" particles into the sky in a way that we can control.
At this point, we need to upgrade from operating one particle to displaying multiple fireworks and multiple particles in each firework on the screen.
Our solution is as follows: create a list, each sublist is a firework, which contains a list of particles. The examples in each list have the same x,y coordinates, size, color, and initial velocity.
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 particle properties are updated regularly. Here we set the particles to update their status every 0.01 seconds and stop updating after 1.8 seconds (this means that each particle exists for 1.6 seconds, of which 1.2 seconds is the "blooming" state and 0.4 seconds is the "falling" state. 0.2 seconds on edge before Tkinter removes it completely).
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
现在,我们只需将最后两个gist合并为一个能被Tkinter调用的函数,就叫它simulate()吧。该函数会展示所有的数据项,并根据我们设置的时间更新每个数据项的属性。在我们的主代码中,我们会用一个alarm处理模块after()调用此函数,after()会等待一定的时间,然后再调用函数。
我们这里设置让Tkinter等待100个单位(1秒钟)再调取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()
好了,这样我们就用Python代码放了一场烟花秀:
本文只一个简单版本,等进一步熟悉Tkinter后,还可以添加更多颜色更漂亮的背景照片,让代码为你绽放更美的烟花!
以下是全部代码:
import tkinter as tk from PIL import Image, ImageTk from time import time, sleep from random import choice, uniform, randint from math import sin, cos, radians # 模拟重力 GRAVITY = 0.05 # 颜色选项(随机或者按顺序) colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen', 'indigo', 'cornflowerblue'] ''' particles 类 粒子在空中随机生成随机,变成一个圈、下坠、消失 属性: - id: 粒子的id - x, y: 粒子的坐标 - vx, vy: 在坐标的变化速度 - total: 总数 - age: 粒子存在的时长 - color: 颜色 - cv: 画布 - lifespan: 最高存在时长 ''' class Particle: 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 = explosion_speed self.vx = vx self.vy = vy self.total = total self.age = 0self.color = color self.cv = cv self.cid = self.cv.create_oval( x - size, y - size, x + size, y + size, fill=self.color) self.lifespan = lifespan def update(self, dt): self.age += dt # 粒子范围扩大 if self.alive() and self.expand(): move_x = cos(radians(self.id * 360 / self.total)) * self.initial_speed move_y = sin(radians(self.id * 360 / self.total)) * self.initial_speed self.cv.move(self.cid, move_x, move_y) self.vx = move_x / (float(dt) * 1000) # 以自由落体坠落 elif self.alive(): move_x = cos(radians(self.id * 360 / self.total)) # we technically don't need to update x, y because move will do the job self.cv.move(self.cid, self.vx + move_x, self.vy + GRAVITY * dt) self.vy += GRAVITY * dt # 移除超过最高时长的粒子 elif self.cid is not None: cv.delete(self.cid) self.cid = None # 扩大的时间 def expand (self): return self.age <= 1.2 # 粒子是否在最高存在时长内 def alive(self): return self.age <= self.lifespan ''' 循环调用保持不停 ''' def simulate(cv): t = time() explode_points = [] wait_time = randint(10, 100) numb_explode = randint(6, 10) # 创建一个所有粒子同时扩大的二维列表 for point in range(numb_explode): objects = [] x_cordi = randint(50, 550) y_cordi = randint(50, 150) speed = uniform(0.5, 1.5) 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 = Particle(cv, idx=i, total=total_particles, explosion_speed=explosion_speed, x=x_cordi, y=y_cordi, vx=speed, vy=speed, color=color, size=size, lifespan=uniform(0.6, 1.75)) objects.append(r) explode_points.append(objects) total_time = .0 # 1.8s内一直扩大 while total_time < 1.8: sleep(0.01) tnew = time() t, dt = tnew, tnew - t for point in explode_points: for item in point: item.update(dt) cv.update() total_time += dt # 循环调用 root.after(wait_time, simulate, cv) def close(*ignore): """退出程序、关闭窗口""" global root root.quit() if __name__ == '__main__': root = tk.Tk() cv = tk.Canvas(root, height=400, width=600) # 选一个好看的背景会让效果更惊艳! image = Image.open("./image.jpg") photo = ImageTk.PhotoImage(image) cv.create_image(0, 0, image=photo, anchor='nw') cv.pack() root.protocol("WM_DELETE_WINDOW", close) root.after(100, simulate, cv) root.mainloop()
众多python培训视频,尽在python学习网,欢迎在线学习!
The above is the detailed content of python cool fireworks confession source code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta
