gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)
帮我写一个烟花的代码
- User
帮我写一个烟花的代码
- Assistant
当然可以!以下是一个简单的 Python 代码示例,用于模拟绘制烟花效果的动画:
import random import turtle # 创建画布 canvas = turtle.Screen() canvas.bgcolor("black") # 创建烟花粒子类 class Particle(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self, shape="circle") self.color(random.choice(["red", "orange", "yellow", "green", "blue", "purple", "pink", "white"])) self.penup() self.speed("fastest") self.shapesize(stretch_wid=0.1, stretch_len=0.1) self.goto(0,-150) self.seth(random.randint(80, 100)) self.dy = random.randint(20, 25) / 10 self.gravity = 0.5 def update(self): self.dy -= self.gravity self.sety(self.ycor() + self.dy) self.setx(self.xcor() + self.dy / 10 * random.choice([-1, 1])) if self.ycor() <= -150: self.dy *= -0.7 self.gravity *= random.uniform(0.9, 1.1) if abs(self.dy) < 0.1: self.goto(0, -150) self.seth(random.randint(80, 100)) self.dy = random.randint(20, 25) / 10 self.gravity = 0.5 # 创建烟花爆炸类 class Firework(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self, shape="square") self.color("white") self.penup() self.goto(random.randint(-150, 150), random.randint(-150, 150)) self.shapesize(stretch_wid=0.2, stretch_len=5) self.speed("fastest") self.dy = random.randint(20, 25) / 10 self.gravity = 0.5 def update(self): self.dy -= self.gravity self.sety(self.ycor() + self.dy) self.setx(self.xcor() + self.dy / 10 * random.choice([-1, 1])) if self.ycor() <= -150: self.dy *= -0.7 self.gravity *= random.uniform(0.9, 1.1) if abs(self.dy) < 0.1: self.explode() def explode(self): for _ in range(50): particle = Particle() particles.append(particle) self.goto(random.randint(-150, 150), random.randint(-150, 150)) self.dy = random.randint(20, 25) / 10 self.gravity = 0.5 # 创建烟花爆炸效果粒子的列表 particles = [] # 创建烟花爆炸效果 firework = Firework() # 动画更新循环 while True: firework.update() for particle in particles: particle.update() # 结束画布 turtle.done()这是一个基本的烟花动画示例,使用了 Python 的 turtle 模块。每次烟花爆炸时,会创建许多小粒子,然后它们会逐渐下落,直到重新形成新的烟花。循环会不断更新所有粒子的位置,以产生动画效果。你可以按照自己的喜好对代码进行修改,并可以添加自己喜欢的细节。希望你能喜欢!