Turtle画树丛,50棵树,左侧的树向左倾斜,右侧的树向右倾斜。
完整代码如下:
import turtle
import random
def draw_tree(pos,hd,angle,len,init_len,level):
t.penup()
t.goto(pos)
t.pendown()
t.setheading(hd)
if pos[0]<0:t.lt(angle)
else:t.rt(angle)
t.fd(len)
p1 = t.position()
d1 = t.heading()
t.penup()
t.goto(pos)
t.setheading(hd)
t.pendown()
if pos[0]<0:t.lt(angle*2)
else:t.rt(angle*2)
t.fd(len)
p2 = t.position()
d2 = t.heading()
if len>init_len-6*level:
draw_tree(p1,d1,angle,len-6,init_len,level)
draw_tree(p2,d2,angle,len-6,init_len,level)
t = turtle.Turtle()
turtle.screensize(800,600)
t.pencolor('black')
turtle.tracer(False)
for i in range(50):
init_len = random.randint(30,60)
level = random.randint(3,5)
pos = (random.randint(-400,400),random.randint(-300,300))
t.setheading(90)
hd = t.heading()
draw_tree(pos,hd,15,init_len,init_len,level)
t.penup()
t.goto(pos)
t.pendown()
t.setheading(90)
turtle.exitonclick()