我需要一个python烟花代码
时间: 2024-02-07 09:02:56 浏览: 66
python程序烟花代码
5星 · 资源好评率100%
以下是一个简单的Python烟花代码,可以在Python 3.x版本中运行:
```python
import random
import time
import turtle
# 设置画布大小和背景颜色
canvas = turtle.Screen()
canvas.setup(width=600, height=600)
canvas.bgcolor("black")
# 创建烟花粒子
class Particle(turtle.Turtle):
def __init__(self, x, y, color):
super().__init__()
self.penup()
self.speed(0)
self.color(color)
self.goto(x, y)
self.shape("circle")
self.shapesize(stretch_wid=0.1, stretch_len=0.1)
self.dx = random.uniform(-2, 2)
self.dy = random.uniform(1, 10)
self.gravity = 0.1
self.life = 50
def move(self):
self.goto(self.xcor() + self.dx, self.ycor() + self.dy - self.gravity)
self.dy -= self.gravity
self.life -= 1
if self.life <= 0:
self.clear()
# 创建烟花
class Firework(turtle.Turtle):
def __init__(self, x, y):
super().__init__()
self.penup()
self.speed(0)
self.color("white")
self.goto(x, y)
self.shape("circle")
self.shapesize(stretch_wid=0.1, stretch_len=0.1)
self.dy = random.uniform(5, 10)
self.life = 100
def move(self):
self.goto(self.xcor(), self.ycor() + self.dy)
self.dy -= 0.1
self.life -= 1
if self.life <= 0:
self.explode()
def explode(self):
for i in range(50):
p = Particle(self.xcor(), self.ycor(), random.choice(["red", "orange", "yellow", "green", "blue", "purple"]))
particles.append(p)
self.clear()
# 创建烟花效果
particles = []
fireworks = []
while True:
if random.random() < 0.1:
f = Firework(random.uniform(-250, 250), -300)
fireworks.append(f)
for f in fireworks:
f.move()
for p in particles:
p.move()
particles = [p for p in particles if not p.isvisible()]
fireworks = [f for f in fireworks if not f.isvisible()]
time.sleep(0.01)
canvas.update()
```
运行该代码将在屏幕上创建一个烟花效果。每隔一段时间,会发射一个烟花并产生粒子效果。可以通过调整代码中的参数来改变烟花的数量、颜色和速度等属性。
阅读全文