python代码画动态樱花
时间: 2023-11-16 20:57:45 浏览: 184
动态樱花可以使用Python的turtle库来实现。下面是一个简单的示例代码:
```
import turtle
import random
# 设置画布大小和背景颜色
turtle.setup(800, 600)
turtle.bgcolor('pink')
# 定义樱花的形状
def sakura():
turtle.begin_fill()
turtle.circle(10, 180)
turtle.circle(25, 110)
turtle.left(50)
turtle.circle(60, 45)
turtle.circle(20, 170)
turtle.right(24)
turtle.fd(30)
turtle.left(10)
turtle.circle(30, 110)
turtle.fd(20)
turtle.left(40)
turtle.circle(90, 70)
turtle.circle(30, 150)
turtle.right(30)
turtle.fd(15)
turtle.circle(80, 90)
turtle.left(15)
turtle.fd(45)
turtle.right(165)
turtle.fd(20)
turtle.left(155)
turtle.circle(150, 80)
turtle.left(50)
turtle.circle(150, 90)
turtle.end_fill()
# 定义花瓣飘落的动画
def petal_fall(petal, speed):
petal.penup()
petal.goto(random.randint(-350, 350), 250)
petal.pendown()
while petal.ycor() > -300:
x = petal.xcor() - random.randint(-5, 5)
y = petal.ycor() - speed
petal.goto(x, y)
# 画出樱花树
trunk = turtle.Turtle()
trunk.hideturtle()
trunk.speed(0)
trunk.penup()
trunk.goto(0, -200)
trunk.pendown()
trunk.color('brown')
trunk.pensize(30)
trunk.left(90)
trunk.fd(200)
trunk.right(180)
trunk.fd(400)
# 画出樱花
petals = []
for i in range(50):
petal = turtle.Turtle()
petal.hideturtle()
petal.speed(0)
petal.color('pink')
petal.pensize(1)
petal.left(random.randint(0, 360))
sakura()
petals.append(petal)
# 花瓣飘落
while True:
for petal in petals:
petal_fall(petal, random.randint(1, 5))
```
阅读全文