Python confession Code: "mountains and rivers are far away, and all fireworks in the world are you, and all are you" (attached source code)

Above

hello everyone! I am 🍑 classmate!

I hope you can support me! ha-ha

Peach, in order to thank everyone who pays attention to me: 💓 The project source code of each article is shared free of charge 💓 See the end of the text!

Many csdn function peaches are still under research, and it's no wonder that the writing of peaches is not good. I will slowly improve and learn from you

Xiaobian has also been learning programming. If there are errors in the code applet, please leave a message in the comment area!

Finally - if the article helps you, remember to "pay attention", "like" and "comment"~

"Is the fireworks lifted off round or flat?"

"Round, flat, strange shape. As long as we are together at this moment."

- Fireworks​​

  🌙 After meeting me, our story began. May you go through mountains and rivers and still feel that the world is worth it 🌙.

Starlight, moonlight and fireworks belong to you, and so do I. About Fireworks 🎇 How much do you} know? How many confessions take place in smoke

Flowers, presumably 👸 Needless to say, everyone knows Ba ~

Today's short passage is about fireworks! Are you ready to enter the fireworks world with me?


Text

"Every copy has a story. Listen carefully."

 

1) Environment installation 🎊

Ready: Python 3, pychar, Tkinter, Pygame, pilot, and some built-in modules.

Unified installation command:

 pip install -i https://pypi.douban.com/simple / + module name

2) Material display 🎨

2.1 music background (optional)

2.2 picture material (modifiable)

3) Formal knock code 🎊

3.1 import and stock in

import random
import pygame as py
import tkinter as tk
from time import time, sleep
from tkinter import filedialog
from PIL import Image, ImageTk
from math import sin, cos, radians
from random import choice, uniform, randint

3.2 interface window setting

if __name__ == '__main__': 
    root = tk.Tk() 
    root.title('Fireworks all over the sky - I wish everyone - lovers will get married')  # Set the title bar of the form
    cv = tk.Canvas(root, height=600, width=600)
    #Draw a canvas 600 high and 600 wide 
    bgpath = filedialog.askopenfilename(title='Please select a background picture')
    #Select background picture
    image = Image.open(bgpath)
    #Open background picture
    image = image.resize((600,600), Image.ANTIALIAS)
    #Resize background image to window size
    photo = ImageTk.PhotoImage(image) 
    cv.create_image(0, 0, image=photo, anchor='nw')
    #Draw the loaded background picture on the canvas 
    bgmusic = filedialog.askopenfilename(title='Please select background music')
    py.mixer.init()
    # initialization
    py.mixer.music.load(bgmusic)
    # File loading
    py.mixer.music.play(-1, 0, fade_ms=50)
    # Play the first one is the play value - 1, which represents the loop play, and the second parameter represents the start time of play
    py.mixer.music.pause() 
    #suspend
    py.mixer.music.unpause()
    #Cancel pause
    cv.pack()
    #Add cv
    root.protocol("WM_DELETE_WINDOW", close)
    root.after(200, simulate, cv)
    #Call the stimulate function after 0.1 seconds to generate a round of fireworks effect
    root.mainloop()
    #Execute root to generate the window

3.3 random color setting

def randomcolor():
    #Generate random colors
    colArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    color = ""
    for i in range(6):
        color += colArr[random.randint(0,14)]
    return "#"+color

GRAVITY = 0.06
#Gravity variable
colors = ['red', 'blue', 'yellow', 'white', 'green', 'orange', 'purple', 'seagreen','indigo', 'cornflowerblue', 'pink']
#Color list
 

3.4 main program fireworks

class part:
#A class object is built separately for each particle blooming from fireworks. Each particle will have some important attributes to determine its appearance (size, color), moving speed, etc
    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
        #Specific identifier of each fireworks
        self.x = x
        #Fireworks bloom x-axis
        self.y = y
        #Fireworks bloom y-axis
        self.initial_speed = explosion_speed
        #Initial particle velocity
        self.vx = vx
        #Particle motion x-axis velocity
        self.vy = vy
        #y-axis velocity of particle motion
        self.total = total
        #Number of blooming particles
        self.age = 0
        #Particle residence time
        self.color = color
        #Particle color
        self.cv = cv
        #canvas
        self.cid = self.cv.create_oval(x - size, y - size, x + size,y + size, fill=self.color, outline='white',width=0.01)
        #Specify a bounding rectangle (Tkinter will automatically draw an ellipse inside this rectangle)
        self.lifespan = lifespan
        #The time the particles stay on the canvas
 
 
    def update(self, dt): 
        self.age += dt
        #Update particle residence time
        if self.alive() and self.expand():
            #If the particle is both alive and expanding
            move_x = cos(radians(self.id*360/self.total))*self.initial_speed
            #The x-axis of particles continues to expand
            move_y = sin(radians(self.id*360/self.total))*self.initial_speed
            #The particle y-axis continues to expand
            self.cv.move(self.cid, move_x, move_y)
            #Move the particles on the canvas x and y distances according to the id
            self.vx = move_x/(float(dt)*1000)
            #Velocity of the particle on the x-axis
       
        
        elif self.alive():
            columnFont = ('Chinese block letters',14)
            #If the particle only survives and does not expand (only the residence time is enough, it indicates that it has expanded to the maximum), it will fall freely
            self.cv.create_text(250, 100, text='happiness',tag="write_tag", fill=choice(colors),font = columnFont) #typeface
            self.cv.create_text(300, 100,  text='Joyous',tag="write_tag", fill=choice(colors),font = columnFont)
            self.cv.create_text(350, 100, text='you',tag="write_tag", fill=choice(colors),font = columnFont)
            self.cv.create_text(400, 100,  text='Acridine',tag="write_tag", fill=choice(colors),font = columnFont)
            #Delete text label
            move_x = cos(radians(self.id*360/self.total))
            #Movement displacement of x-axis
            # 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
            #Update y axis
 

        elif self.cid is not None:
            #If the particle's life cycle has passed, remove it
            cv.delete(self.cid)
            #Remove the particle object on the canvas
            self.cv.delete("write_tag")
            #Remove fonts at the same time
            self.cid = None
 
 
 
    def expand (self):
        #Defines the time frame for the bulge effect
        return self.age <= 1.2
        #Judge whether the expansion time is less than 1.2 seconds
 
 
 
    def alive(self):
        #Determine whether the particle is still in its life cycle
        return self.age <= self.lifespan
        #Judge whether the dwell time is less than the expected dwell time
 
 
'''
Firework simulation loop:
Recursively call to repeatedly emit new fireworks on canvas
a list of list (list of stars, each of which is a list of particles)
is created and drawn on canvas at every call, 
via update protocol inside each 'part' object 
'''
 
def simulate(cv):
 
    t = time()
    #Returns the number of floating-point seconds since 1970, accurate to 7 decimal places
    explode_points = []
    #Explosion point list, fireworks list
    wait_time = randint(10,100)
    #The waiting time is an integer between 10 and 100
    numb_explode = randint(8,20)
    #The number of explosive fireworks is a random integer between 6 and 10
    # create list of list of all particles in all simultaneous explosion
    for point in range(numb_explode):
        #Create a list of all particles that simulate a fireworks bloom
        if point<=4:
            objects = []
            #List of exploding particles per point
            x_cordi = 250 + point*50
            #x axis of each explosion point
            y_cordi = 100
            #y axis of each explosion point
            speed = uniform (0.5, 1.5)          
            #Speed of each explosion point
            size = uniform (0.5,3)
            #Size of each explosion point
            color = choice(colors)
            #Color of each explosion point
            explosion_speed = uniform(0.6, 3)
            #Explosion blooming speed
            total_particles = randint(10,60)
            #Total number of particles in fireworks
            for i in range(1,total_particles):
            #The particle size, velocity and coordinates of the same fireworks explosion are the same
                r = part(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))
                #The above parameters are substituted into the part function, but the survival time of each particle is independent
                objects.append(r)
                #Add r to the particle list
            explode_points.append(objects)
            #Add particle list to fireworks list
        else: 
            objects = []
            #List of exploding particles per point
            x_cordi = randint(50,550)
            #x axis of each explosion point
            y_cordi = randint(50, 150)
            #y axis of each explosion point
            speed = uniform (0.5, 1.5)          
            #Speed of each explosion point
            size = uniform (0.5,3)
            #Size of each explosion point
            color = choice(colors)
            #Color of each explosion point
            explosion_speed = uniform(0.3, 2)
            #Explosion blooming speed
            total_particles = randint(10,50)
            #Total number of particles in fireworks
            for i in range(1,total_particles):
            #The particle size, velocity and coordinates of the same fireworks explosion are the same
                r = part(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))
                #The above parameters are substituted into the part function, but the survival time of each particle is independent
                objects.append(r)
                #Add r to the particle list
            explode_points.append(objects)
            #Add particle list to fireworks list

 
    total_time = .0
    #Total initialization time
    # keeps undate within a timeframe of 1.8 second 
    while total_time < 2:
    #Run the cycle when the total time is less than 1.8 seconds
        sleep(0.03)
        #Pause the screen for 0.01 seconds
        tnew = time()
        #Refresh time
        t, dt = tnew, tnew - t
        #The time is equal to the new time and the last time interval is tnew-t
        for point in explode_points:
        #Traverse the fireworks list
            for item in point:
            #Traverse the list of particles in fireworks
                item.update(dt)
                #Particle update time
        cv.update()
        #Refresh canvas
        total_time += dt
        #Add time to the while loop
 
    root.after(wait_time, simulate, cv)
    #Place the component after other components, put it on the top layer, cover the lower, and call itself recursively to form a new round of explosion

def close(*ignore):
    #Open the simulation loop and close the window
    """Stops simulation loop and closes the window."""
    global root
    root.quit()

4) effect display 💐

Show four groups of fireworks effects - try the rest with your own code~ 🎇 In fact, they are dynamic fireworks drops~

1, PART 01 🌻

1.0 random works display effect ❤

1.2 fireworks Copywriting - stars in the sky 🌙

✨ If you don't have enough stars, let's show you fireworks

✨ Fireworks are beautiful. Your smile is more beautiful when you look at fireworks and smile

✨ You showed me a fireworks. Your smile is in my dream

✨ If time is intoxicating fireworks, can you see the bright wind with me

✨ Sweetheart has his fireworks, sweetheart is your eyes have fire

I will luve thee still, my dear.

While the sands o' life shall run.​

2, PART 02 🌻

1.0 random works display effect ❤

1.2 fireworks copy - Sansheng fireworks 🌙

✨ A fairy stick can burn for 9 seconds and instantly release 180 flames, more than the stars in the Milky way, so I called you out to set off fireworks

Give you the stars

✨ Watch the fireworks bloom alone and keep the fireworks cool

✨ Fireworks are fleeting, but ashes are eternal

✨ I use three fireworks to return your confusion for life

✨ You, once such beautiful fireworks were in full bloom in my sky. When the fireworks dissipated, I found only one ground at the ruins

Fracture

I will luve thee still, my dear.

While the sands o' life shall run.

III. PART 03 🌻

1.0 display effect of random works ❤

1.2 fireworks Copywriting - shilichang Street 🌙

✨ Since then, fireworks, more than a moment, such as my blessing, will not fall with the lonely moment

✨ Your appearance is like fireworks in the middle of the night. Although it is only for a moment, it illuminates my whole life

✨ Ten miles of Hantan Road, half of the fireworks wake up

✨ Fireworks bloom, slowly look up, lonely without sleep, Siqing heartbroken

✨ Long streets are long and fireworks are numerous. You look back with lights. Short pavilions are short and the world of mortals is rolling. I sigh again

I will luve thee still, my dear.

While the sands o' life shall run.

4, PART 04 🌻

1.0 display effect of random works ❤

1.2 , fireworks Copywriting - ten thousand years at a glance 🌙

✨ Fireworks are forever, because it engraves eternal beauty in my heart. Fireworks are happy because of the moment it leaves behind

Affirmed their beauty

✨ When I like you, my heart is full of small fireworks. Well, when the fireworks are in full bloom this year, let me jump into your arms

OK or not?

✨ We must watch a fireworks conference with you and feel a romantic and exciting experience

✨ Fireworks bloom brilliantly, a moment is a lifetime. The heart of protection is firm, and the millennium is close at hand

✨ The moment of youth is like quicksand at the fingertips. Brilliant fireworks can't be cut after all

I will luve thee still, my dear.

While the sands o' life shall run.

summary

"There are girls who don't like flowers and don't love romance"! This is the end of the article ~ take the code to express or give it to the object!

If you need complete information, I can ha or click here! Portal

Your support is my biggest motivation!! Remember the third company~

Keywords: Python Programmer Tkinter

Added by pachanga1 on Wed, 05 Jan 2022 07:41:05 +0200