今天给大家分享2个烟花效果代码

希望大家平平安安,身体健康!

并且是第一次在这里创作!

1.ui类

代码:

import tkinter as tk
import random
import math

WIDTH, HEIGHT = 900, 600
GRAVITY = 0.08
TRAIL_LENGTH = 12

class Particle:
    def __init__(self, x, y, vx, vy, color, lifetime=60, size=3):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy
        self.color = color
        self.lifetime = lifetime
        self.max_lifetime = lifetime
        self.size = size
        self.trail = []

    def update(self):
        self.trail.append((self.x, self.y))
        if len(self.trail) > TRAIL_LENGTH:
            self.trail.pop(0)
        self.x += self.vx
        self.y += self.vy
        self.vy += GRAVITY
        self.vx *= 0.98
        self.lifetime -= 1

    def is_dead(self):
        return self.lifetime <= 0

    def alpha_color(self, base_color, alpha_ratio):
        r = int(int(base_color[1:3], 16) * alpha_ratio)
        g = int(int(base_color[3:5], 16) * alpha_ratio)
        b = int(int(base_color[5:7], 16) * alpha_ratio)
        return f'#{r:02x}{g:02x}{b:02x}'


class Rocket:
    def __init__(self, x):
        self.x = x
        self.y = HEIGHT - 10
        self.vy = random.uniform(-14, -10)
        self.trail = []
        self.exploded = False

    def update(self):
        self.trail.append((self.x, self.y))
        if len(self.trail) > 8:
            self.trail.pop(0)
        self.y += self.vy
        self.vy += GRAVITY * 0.5
        if self.vy >= 0:
            self.exploded = True

    def is_done(self):
        return self.exploded


PALETTES = [
    ['#ff4444', '#ff8800', '#ffdd00'],
    ['#00ccff', '#0066ff', '#aa00ff'],
    ['#00ff88', '#00ffcc', '#88ff00'],
    ['#ff44cc', '#ff0088', '#ff66aa'],
    ['#ffffff', '#ffeeaa', '#ffcc44'],
    ['#ff6600', '#ff3300', '#ffaa00'],
]


class FireworksApp:
    def __init__(self, root):
        self.root = root
        root.title("🎆 Fireworks")
        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='#000008', highlightthickness=0)
        self.canvas.pack()
        self.particles = []
        self.rockets = []
        self.stars = [(random.randint(0, WIDTH), random.randint(0, HEIGHT//2),
                       random.choice(['#ffffff', '#aaaacc', '#eeeeff'])) for _ in range(120)]
        self.tick = 0
        self.animate()

    def launch_rocket(self):
        x = random.randint(WIDTH//6, 5*WIDTH//6)
        self.rockets.append(Rocket(x))

    def explode(self, x, y):
        palette = random.choice(PALETTES)
        count = random.randint(80, 130)
        style = random.choice(['burst', 'ring', 'star', 'double'])

        for i in range(count):
            angle = (2 * math.pi * i / count) + random.uniform(-0.1, 0.1)
            if style == 'ring':
                speed = random.uniform(3.5, 4.5)
            elif style == 'star':
                speed = 4.5 if i % (count // 5) == 0 else random.uniform(1.5, 3.0)
            elif style == 'double':
                speed = random.choice([random.uniform(1.5, 2.5), random.uniform(4, 5.5)])
            else:
                speed = random.uniform(0.5, 5.5)

            vx = math.cos(angle) * speed
            vy = math.sin(angle) * speed
            color = random.choice(palette)
            lifetime = random.randint(45, 80)
            size = random.randint(2, 4)
            self.particles.append(Particle(x, y, vx, vy, color, lifetime, size))

        # Sparkle center
        for _ in range(20):
            vx = random.uniform(-1.5, 1.5)
            vy = random.uniform(-1.5, 1.5)
            self.particles.append(Particle(x, y, vx, vy, '#ffffff', 30, 2))

    def draw(self):
        self.canvas.delete('all')

        # Stars
        for sx, sy, sc in self.stars:
            self.canvas.create_oval(sx-1, sy-1, sx+1, sy+1, fill=sc, outline='')

        # Ground glow
        self.canvas.create_rectangle(0, HEIGHT-4, WIDTH, HEIGHT, fill='#111133', outline='')

        # Rocket trails
        for rocket in self.rockets:
            for i, (tx, ty) in enumerate(rocket.trail):
                alpha = (i + 1) / len(rocket.trail)
                size = max(1, int(3 * alpha))
                color = f'#{int(255*alpha):02x}{int(140*alpha):02x}00'
                self.canvas.create_oval(tx-size, ty-size, tx+size, ty+size, fill=color, outline='')
            # Rocket head
            self.canvas.create_oval(rocket.x-3, rocket.y-3, rocket.x+3, rocket.y+3,
                                    fill='#ffff88', outline='')

        # Particles
        for p in self.particles:
            alpha = p.lifetime / p.max_lifetime
            color = p.alpha_color(p.color, alpha)
            s = max(1, p.size * alpha)
            self.canvas.create_oval(p.x-s, p.y-s, p.x+s, p.y+s, fill=color, outline='')
            # Trail
            if len(p.trail) > 1:
                for i in range(1, min(5, len(p.trail))):
                    tx, ty = p.trail[-i]
                    ta = alpha * (1 - i/6)
                    tc = p.alpha_color(p.color, ta)
                    ts = max(1, s * (1 - i/6))
                    self.canvas.create_oval(tx-ts, ty-ts, tx+ts, ty+ts, fill=tc, outline='')

    def animate(self):
        self.tick += 1

        if self.tick % random.randint(30, 60) == 0:
            self.launch_rocket()

        for rocket in self.rockets[:]:
            rocket.update()
            if rocket.is_done():
                self.explode(rocket.x, rocket.y)
                self.rockets.remove(rocket)

        for p in self.particles[:]:
            p.update()
            if p.is_dead():
                self.particles.remove(p)

        self.draw()
        self.root.after(16, self.animate)  # ~60fps


if __name__ == '__main__':
    root = tk.Tk()
    app = FireworksApp(root)
    root.mainloop()

这个代码不需要外部库——它只使用tkinter(内置于Python中)。以下是它的特点:

有烟花发射的效果,并且很不错!
 

效果:

2.使用turtle

代码:

import turtle
import random
import time

t = turtle.Turtle()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")

colors = ["red", "yellow", "blue", "purple", "orange", "cyan", "white"]

def firework(x, y):
    t.penup()
    t.goto(x, y)
    t.pendown()

    color = random.choice(colors)
    t.color(color)

    for _ in range(36):
        t.forward(random.randint(50, 100))
        t.backward(random.randint(50, 100))
        t.right(10)

while True:
    x = random.randint(-300, 300)
    y = random.randint(-200, 200)
    firework(x, y)
    time.sleep(0.5)

这个代码无需安装任何库,Python 自带
👉 原理清晰,适合学习

注意这个代码是无限循环的!

效果:

注:本文章中的代码使用ai生成,仅供参考

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐