python 写个烟花
以下是一个简单的Python烟花程序的示例代码:
import turtle
import random
# 创建一个烟花类
class Firework:
def __init__(self, color):
self.color = color
self.x = random.randint(-200, 200)
self.y = random.randint(-200, 200)
self.dy = random.randint(1, 5)
self.size = random.randint(1, 5)
def explode(self):
for _ in range(20):
spark = turtle.Turtle()
spark.shape("circle")
spark.color(self.color)
spark.shapesize(self.size / 10)
spark.penup()
spark.goto(self.x, self.y)
spark.dy = random.randint(-10, 10)
spark.dx = random.randint(-10, 10)
while spark.y > -200:
spark.dy -= 0.1
spark.sety(spark.y + spark.dy)
spark.setx(spark.x + spark.dx)
# 创建一个画布
canvas = turtle.Screen()
canvas.bgcolor("black")
# 创建一个烟花列表
fireworks = []
# 创建烟花函数
def create_firework():
color = random.choice(["red", "blue", "green", "yellow", "purple", "orange", "pink"])
firework = Firework(color)
fireworks.append(firework)
# 创建画布更新函数
def update():
canvas.clear()
for firework in fireworks:
firework.explode()
fireworks.remove(firework)
canvas.update()
canvas.ontimer(update, 50)
# 创建主函数
def main():
canvas.onclick(lambda x, y: create_firework())
update()
turtle.done()
# 执行主函数
if __name__ == "__main__":
main()
运行这段代码,你可以点击画布的任意位置创建一个烟花,并观察它的爆炸效果。每个烟花将在爆炸后逐渐消失。希望这个例子对你有帮助
原文地址: http://www.cveoy.top/t/topic/hJiR 著作权归作者所有。请勿转载和采集!