Python绝美樱花树
import turtle
import random
import time# 设置画笔速度
turtle.speed(0)
# 隐藏画笔
turtle.hideturtle()
# 设置背景颜色为淡蓝色,模拟天空
turtle.bgcolor("#e0f7fa")# 定义颜色列表,用于花瓣的颜色渐变
petal_colors = ["#ffe4e1", "#ffc0cb", "#ff99aa", "#ff6677", "#ff3344"]# 定义绘制树干和树枝的函数
def draw_branch(length, angle, width):
if length < 5:
return
turtle.pensize(width)
turtle.forward(length)
new_angle = angle + random.uniform(-10, 10)
new_length = length * random.uniform(0.6, 0.8)
new_width = width * 0.8
turtle.right(new_angle)
draw_branch(new_length, new_angle, new_width)
turtle.left(2 * new_angle)
draw_branch(new_length, new_angle, new_width)
turtle.right(new_angle)
turtle.backward(length)# 定义绘制不同形状樱花花瓣的函数
def draw_petal(x, y, shape_type):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.color(random.choice(petal_colors))
turtle.begin_fill()
if shape_type == 0: # 圆形花瓣
turtle.circle(8)
elif shape_type == 1: # 椭圆形花瓣
for _ in range(2):
turtle.circle(10, 180)
turtle.left(120)
elif shape_type == 2: # 不规则花瓣
for _ in range(4):
turtle.forward(10)
turtle.right(90)
turtle.circle(5, 180)
turtle.end_fill()# 定义让花瓣飘落的函数
def petal_fall():
all_petals = []
for _ in range(50):
x = random.randint(-200, 200)
y = random.randint(100, 200)
shape_type = random.randint(0, 2)
petal = {
"x": x,
"y": y,
"shape_type": shape_type,
"speed": random.uniform(0.5, 2)
}
all_petals.append(petal)for _ in range(100):
turtle.clear()
draw_branch(100, 20, 5)
for petal in all_petals:
draw_petal(petal["x"], petal["y"], petal["shape_type"])
petal["y"] -= petal["speed"]
if petal["y"] < -200:
petal["x"] = random.randint(-200, 200)
petal["y"] = random.randint(100, 200)
time.sleep(0.1)
# 移动到绘制树干的起始位置
turtle.penup()
turtle.goto(0, -200)
turtle.pendown()
turtle.left(90)
# 绘制树干和树枝
draw_branch(100, 20, 5)
# 绘制一些初始的樱花花瓣
for _ in range(100):
x = random.randint(-200, 200)
y = random.randint(-100, 100)
shape_type = random.randint(0, 2)
draw_petal(x, y, shape_type)
# 让花瓣飘落
petal_fall()
# 暂停一段时间以便查看绘制结果
time.sleep(5)
1. 增加了背景颜色设置为淡蓝色,模拟天空的效果。
2. 定义了 petal_colors 列表,让花瓣颜色有渐变效果,每次绘制花瓣时随机选择一种颜色。
3. draw_petal 函数增加了不同的花瓣形状绘制逻辑,通过 shape_type 参数来控制绘制圆形、椭圆形或不规则形状的花瓣。
4. 新增了 petal_fall 函数,实现了花瓣飘落的动画效果,让樱花树看起来更加生动。每次循环时会清除画布重新绘制树干、树枝和当前位置的花瓣,并更新花瓣的位置,当花瓣落到一定位置后重新随机生成位置。