Python and pygame implement fireworks special effects

Python and pygame implement fireworks special effects

As the New Year approaches, let’s celebrate the New Year with fireworks. You need to install and use the third-party library pygame. You can see the installation and use of the pygame game module in Pythonhttps://blog .csdn.net/cnds123/article/details/119514520

Renderings and source code

Let’s look at the renderings first:

The source code is as follows:

import pygame
import random
import math

# 初始化pygame
pygame.init()

# 设置窗口大小
width, height = 800, 600
screen = pygame.display.set_mode((width, height))

# 定义颜色
black = (0, 0, 0)
red = (255, 0, 0)

# 定义烟花粒子
class Particle:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color
        self.radius = random.randint(2, 4)
        self.angle = random.uniform(0, 2 * math.pi)
        self.speed = random.uniform(1, 3)
        self.gravity = 0.1

    def move(self):
        self.x += math.cos(self.angle) * self.speed
        self.y += math.sin(self.angle) * self.speed + self.gravity
        self.radius -= 0.1  # 粒子逐渐变小

    def draw(self):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), int(self.radius))

# 定义烟花
class Firework:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        self.particles = []
        self.exploded = False
        self.explode_height = random.randint(100, 400)  # 设置爆炸高度

        self.speed = random.randint(5, 10)  # 设置上升速度
        self.angle = math.pi / 2  # 设置上升角度为垂直向上

    def launch(self):
        if not self.exploded:
            self.y -= self.speed * math.sin(self.angle)
            if self.y <= self.explode_height:  # 到达设定高度后爆炸
                self.explode()
                self.exploded = True

    def explode(self):
        for _ in range(100):  # 爆炸产生的粒子数量
            self.particles.append(Particle(self.x, self.y, self.color))

    def draw(self):
        if not self.exploded:
            pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 5)
        else:
            for particle in self.particles:
                particle.move()
                particle.draw()

#显示文字
#font = pygame.font.Font(None, 36)  # 设置字体和大小                
font = pygame.font.Font("C:\\Windows\\Fonts\\simsun.ttc", 36)        
text = font.render("龙年快乐", True, red)  # 渲染文本
text_rect = text.get_rect(center=(width // 2, height // 2))  # 获取文本的矩形区域

# 主循环
fireworks = []
clock = pygame.time.Clock()
running = True
while running:
    clock.tick(30)  # 控制帧率
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill(black)

    # 绘制文本
    screen.blit(text, text_rect)

    # 发射烟花
    if random.randint(1, 20) == 1:  # 控制烟花发射频率
        fireworks.append(Firework(random.randint(0, width), height))

    # 更新烟花并绘制
    for firework in fireworks[:]:
        firework.launch()
        firework.draw()
        if firework.exploded and all(p.radius <= 0 for p in firework.particles):
            fireworks.remove(firework)

    pygame.display.flip()

pygame.quit()

Description of how pygame displays fonts on the screen

Use the pygame.font.Font function to set the font and size, then use the font.render function to render the text as an image. Finally, use the screen.blit function to draw the rendered text image to the screen.

pygame.font.Font(None, font size) uses the system default font and may not support Chinese characters. None represents the system default font, such as pygame.font.Font(None, 36), which may not support Chinese characters. what to do? Use pygame.font.Font("Font name with path", font size) to specify a font that supports Chinese characters, such as: pygame.font.Font("C:\\Windows\\Fonts\\simsun.ttc", 36), simsun.ttc is Song Dynasty, the path and name of the font. How to determine the path and name of fonts in Windows? See picture below

Improvement: Add background music to add a happy atmosphere

Before the "# Main Loop" section, add the following code

# Load background music
pygame.mixer.music.load("Stepping to a happy rhythm - Orange Light Music.mp3")
pygame.mixer.music.set_volume(0.5) # Set the volume
pygame.mixer.music.play(-1) # Play background music, -1 means loop play

Among them, the pygame.mixer.music.load function loads the background music file (for example, the file named "Stepping on the Happy Rhythm - Orange Light Music.mp3" and places it inIn the same directory as the code file), then use the pygame.mixer.music.set_volume function to set the volume (range is 0.0-1.0). Finally, use the pygame.mixer.music.play function to play background music. The parameter -1 indicates loop playback.

Please use your own background music file to replace "Stepping on the Happy Rhythm - Orange Light Music.mp3", just make sure the file name and path are correctly named.

Guess you like

Origin blog.csdn.net/cnds123/article/details/134974517