python炫酷烟花表白源代码-代码也浪漫:用Python放一场烟花秀!
时间: 2024-02-25 09:59:05 浏览: 112
好的,这是Python炫酷烟花表白的源代码:
```python
import turtle
import random
import time
# 定义一个烟花类
class Firework:
def __init__(self, x, y, vx, vy, ax, ay, color):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.ax = ax
self.ay = ay
self.color = color
self.is_explode = False
self.particles = []
# 更新烟花粒子位置
def update_particles(self):
for p in self.particles:
p.vx += p.ax
p.vy += p.ay
p.x += p.vx
p.y += p.vy
p.ttl -= 1
# 更新烟花位置
def update(self):
if not self.is_explode:
self.vy += self.ay
self.vx += self.ax
self.x += self.vx
self.y += self.vy
if self.vy <= 0:
self.explode()
else:
self.update_particles()
# 烟花爆炸
def explode(self):
self.is_explode = True
for _ in range(50):
speed = random.uniform(0.5, 1.5)
angle = random.uniform(0, 2 * 3.14)
vx = speed * math.cos(angle)
vy = speed * math.sin(angle)
p = Particle(self.x, self.y, vx, vy, -0.01, self.color)
self.particles.append(p)
# 判断是否烟花已经燃尽
def is_dead(self):
if self.is_explode:
return all([p.ttl <= 0 for p in self.particles])
else:
return self.vy <= 0
# 定义一个烟花粒子类
class Particle:
def __init__(self, x, y, vx, vy, ay, color):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.ay = ay
self.ttl = random.randint(50, 80)
self.color = color
# 实例化一个画布
canvas = turtle.Screen()
# 设置画布大小
canvas.setup(800, 600)
# 设置画笔速度
turtle.speed(0)
# 隐藏画笔
turtle.hideturtle()
# 关闭画笔轨迹
turtle.tracer(False)
# 定义烟花列表
fireworks = []
# 定义画笔颜色列表
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'white']
# 定义计数器
count = 0
# 循环绘制烟花
while True:
# 每隔5次循环添加一个新的烟花
if count % 5 == 0:
x = random.randint(-400, 400)
y = -300
vx = random.uniform(-1, 1)
vy = random.uniform(15, 25)
ax = 0
ay = -0.1
color = random.choice(colors)
f = Firework(x, y, vx, vy, ax, ay, color)
fireworks.append(f)
# 清空画布
turtle.clear()
# 绘制所有烟花和粒子
for f in fireworks:
turtle.penup()
turtle.goto(f.x, f.y)
turtle.pendown()
turtle.dot(10, f.color)
if f.is_explode:
for p in f.particles:
turtle.penup()
turtle.goto(p.x, p.y)
turtle.pendown()
turtle.dot(5, p.color)
# 更新烟花状态
f.update()
# 判断烟花是否已经燃尽
if f.is_dead():
fireworks.remove(f)
# 更新画布
turtle.update()
# 计数器加1
count += 1
# 等待一段时间
time.sleep(0.02)
```
当你运行这段代码,你会看到一个有趣的烟花秀,希望你喜欢!
阅读全文