借鉴如下画一颗树的代码,用函数调用的形式,画出一批森林from turtle import Turtle, mainloop def tree(plist, l, a, f): """ plist is list of pens l is length of branch a is half of the angle between 2 branches f is factor by which branch is shortened from level to level.""" if l > 5: # lst = [] for p in plist: p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed. q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties. p.left(a) #Turn turtle left by angle units q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions. lst.append(p)#将元素增加到列表的最后 lst.append(q) tree(lst, l*f, a, f)
时间: 2024-02-14 13:17:27 浏览: 123
好的,我理解了你的要求。以下是基于函数调用的森林绘制代码,你可以在调用时传入不同的参数以绘制不同形态的森林:
```
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5:
lst = []
for p in plist:
p.forward(l)
q = p.clone()
p.left(a)
q.right(a)
lst.append(p)
lst.append(q)
tree(lst, l*f, a, f)
def forest(n, m, l, a, f):
""" n is the number of trees in the forest
m is the number of levels of each tree
l is the initial length of the branches
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
for i in range(n):
t = Turtle()
t.hideturtle()
t.speed(0)
t.left(90)
t.penup()
t.goto(-400 + i*200, -200)
t.pendown()
plist = [t]
for j in range(m):
tree(plist, l, a, f)
plist = plist[1::2]
t.penup()
forest(3, 5, 100, 30, 0.7)
mainloop()
```
在调用 `forest` 函数时,你可以传入不同的参数来控制绘制的森林:
- `n`:森林中树的数量
- `m`:每棵树的层数
- `l`:树枝的初始长度
- `a`:每个交叉点的夹角
- `f`:每一层树枝长度相对于上一层的缩小比例
例如,`forest(3, 5, 100, 30, 0.7)` 会绘制出三棵树,每棵树有五层,初始树枝长度为 100,每个交叉点夹角为 30 度,每一层长度相对于上一层的缩小比例为 0.7。
阅读全文