需求
使用python的turtle库绘制圣诞树
绘制结果
代码实现
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
def draw_christmas_tree(ax):
# 定义树的基本参数
base_width = 6 # 底部宽度
height = 12 # 总高度
levels = 3 # 层次数量
# 计算每一层的顶点坐标
vertices = []
for i in range(levels):
width = base_width * (levels - i) / levels
top_y = height * (i + 1) / levels
bottom_y = height * i / levels
left_x = 3 - width / 2
right_x = 3 + width / 2
vertices.append([(left_x, bottom_y), (right_x, bottom_y), (3, top_y)])
# 绘制每一层
for v in vertices:
polygon = patches.Polygon(v, closed=True, fill=True, color='green', zorder=1) # 设置zorder
ax.add_patch(polygon)
# 绘制树干
trunk = patches.Rectangle((2.5, -1), 1, 2, linewidth=1, edgecolor='brown', facecolor='brown', zorder=1) # 设置zorder
ax.add_patch(trunk)
# 添加装饰品
num_decorations = 30 # 装饰品数量
decoration_colors = ['red', 'blue', 'yellow', 'white'] # 装饰品颜色
decorations = [] # 存储装饰品的位置
for _ in range(num_decorations):
# 随机生成装饰品的位置,确保它们位于树上
x = np.random.uniform(1, 5)
y = np.random.uniform(0, height)
while not is_on_tree(x, y, vertices):
x = np.random.uniform(1, 5)
y = np.random.uniform(0, height)
decorations.append((x, y))
# 在所有树的部分绘制完成后,添加装饰品
for x, y in decorations:
ax.scatter(x, y, s=50, c=np.random.choice(decoration_colors), zorder=2) # 设置更高的zorder
# 设置坐标轴的范围
ax.set_xlim(0, 6)
ax.set_ylim(-2, 12)
ax.axis('off')
def is_on_tree(x, y, vertices):
"""检查装饰品是否位于树上"""
for v in vertices:
if (v[0][0] <= x <= v[1][0]) and (v[0][1] <= y <= v[2][1]):
return True
return False
# 创建一个新的图形
fig, ax = plt.subplots()
# 调用函数绘制圣诞树
draw_christmas_tree(ax)
# 显示图形
plt.show()