使用Python的turtle模块实现简单的烟花效果

import turtle
import random
import math

# 设置窗口大小
width, height = 800, 600
screen = turtle.Screen()
screen.title("Fireworks Explosion")
screen.bgcolor("black")
screen.setup(width, height)

# 定义烟花粒子类
class Particle(turtle.Turtle):
    def __init__(self, x, y, color):
        super().__init__()
        self.penup()
        self.goto(x, y)
        self.color(color)
        self.shape("circle")
        self.shapesize(0.2)  # 粒子大小
        self.angle = random.uniform(0, 2 * math.pi)
        self.speed = random.uniform(2, 5)
        self.setheading(self.angle * 180 / math.pi)
        self.showturtle()

    def move(self):
        self.speed *= 0.97  # 添加速度衰减效果
        x, y = self.position()
        self.goto(x + self.speed * math.cos(self.angle), y + self.speed * math.sin(self.angle))

def create_firework_explosion():
    explosion_color = random.choice(colors)
    x = 0  # 将烟花放在屏幕中央的水平位置
    y = 0  # 将烟花放在屏幕中央的垂直位置
    for _ in range(100):
        particles.append(Particle(x, y, explosion_color))

# 主循环
particles = []
colors = ["red", "green", "blue", "yellow", "purple", "cyan"]
screen.tracer(0)  # 关闭自动更新屏幕

while True:
    # 产生新的烟花爆炸
    if random.random() < 0.02:
        create_firework_explosion()

    # 更新烟花粒子位置
    for particle in particles:
        particle.move()

    # 移除离开屏幕的烟花粒子
    particles = [particle for particle in particles if -width//2 <= particle.xcor() <= width//2 and -height//2 <= particle.ycor() <= height//2]

    screen.update()  # 手动更新屏幕显示
    turtle.delay(10)  # 控制更新速度

注意,在turtle中,每个Particle实例都是一个turtle.Turtle()对象,这可能会在生成大量粒子时导致程序变慢。此外,由于turtle的事件循环机制,这个程序缺少一个简单的退出机制,可能需要添加一个按钮或者监听某个键盘事件来退出程序。

上述代码提供了一个基本框架,展示了如何使用turtle模块来模拟烟花效果。

要优化使用turtle模块的烟花效果代码,我们可以采取以下策略:

  1. 减少每次爆炸生成的粒子数量以提高性能。
  2. 使用ontimer方法代替死循环来控制动画的更新,这样可以避免程序无响应。
  3. 添加一个退出机制,让用户可以通过点击窗口来退出程序。

优化后代码:

import turtle
import random
import math

# 设置窗口大小
width, height = 800, 600
screen = turtle.Screen()
screen.title("Fireworks Explosion")
screen.bgcolor("black")
screen.setup(width, height)

# 定义烟花粒子类
class Particle(turtle.Turtle):
    def __init__(self, x, y, color):
        super().__init__()
        self.hideturtle()
        self.penup()
        self.goto(x, y)
        self.color(color)
        self.shape("circle")
        self.shapesize(0.2)  # 粒子大小
        self.angle = random.uniform(0, 2 * math.pi)
        self.speed = random.uniform(2, 5)
        self.setheading(self.angle * 180 / math.pi)
        self.showturtle()

    def move(self):
        self.speed *= 0.97  # 添加速度衰减效果
        x, y = self.position()
        self.goto(x + self.speed * math.cos(self.angle), y + self.speed * math.sin(self.angle))

def create_firework_explosion():
    explosion_color = random.choice(colors)
    x = 0  # 将烟花放在屏幕中央的水平位置
    y = 0  # 将烟花放在屏幕中央的垂直位置
    for _ in range(50):  # 减少粒子数量以提高性能
        particles.append(Particle(x, y, explosion_color))
    update_fireworks()

def update_fireworks():
    global particles
    screen.update()  # 手动更新屏幕显示
    # 更新烟花粒子位置
    for particle in particles:
        particle.move()

    # 移除离开屏幕的烟花粒子
    particles = [particle for particle in particles if -width//2 <= particle.xcor() <= width//2 and -height//2 <= particle.ycor() <= height//2]

    # 产生新的烟花爆炸
    if random.random() < 0.05:  # 调整概率以控制爆炸频率
        create_firework_explosion()
    else:
        screen.ontimer(update_fireworks, 50)  # 使用ontimer来递归调用更新函数

def exit_program(x, y):
    screen.bye()

# 主逻辑
particles = []
colors = ["red", "green", "blue", "yellow", "purple", "cyan"]
screen.tracer(0)  # 关闭自动更新屏幕

screen.onclick(exit_program)  # 点击窗口时退出程序

update_fireworks()  # 开始更新烟花

turtle.done()

上述代码通过减少每次爆炸生成的粒子数量来提高性能,并且使用screen.ontimer(update_fireworks, 50)代替了死循环来控制动画的更新。

这样做不仅提高了程序的响应性,也使得通过点击窗口就可以退出程序了。

注意,虽然这些优化可以提高程序的表现,但是当屏幕上有大量粒子时,turtle模块的性能限制可能仍然会导致动画变得不够流畅。进一步的优化可能需要减少动画复杂度或者考虑使用其他更适合动画制作的库,比如Pygame。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python 烟花代码是一种用Python编写的模拟烟花爆炸效果的程序。它通过绘制图形和模拟物理效果实现烟花的动态效果。 以下是一个简单Python烟花代码示例: ```python import random import turtle # 创建画布 canvas = turtle.Screen() canvas.bgcolor("black") # 创建烟花粒子类 class Particle(turtle.Turtle): def __init__(self, color): turtle.Turtle.__init__(self) self.shape("circle") self.color(color) self.penup() def launch(self): self.goto(0, -200) self.setheading(random.randint(0, 360)) self.speed(10) self.showturtle() def explode(self): self.hideturtle() for _ in range(20): self.color(random.choice(["red", "orange", "yellow", "green", "blue", "purple"])) self.goto(random.randint(-300, 300), random.randint(-300, 300)) self.showturtle() # 创建烟花管理类 class FireworkManager: def __init__(self): self.particles = [] def launch_firework(self): particle = Particle("white") particle.launch() self.particles.append(particle) def explode_firework(self): for particle in self.particles: particle.explode() # 创建烟花管理器对象 manager = FireworkManager() # 发射烟花 manager.launch_firework() # 等待一段时间后,烟花爆炸 turtle.delay(1000) manager.explode_firework() # 关闭画布 turtle.done() ``` 这段代码使用Pythonturtle库来绘制图形,并通过模拟粒子的运动和爆炸效果实现烟花的动态效果。代码中定义了一个烟花粒子类Particle,以及一个烟花管理类FireworkManager。通过调用FireworkManager的launch_firework方法来发射烟花,然后等待一段时间后调用explode_firework方法使烟花爆炸。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北辰星Charih

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值