Home > other >  The turtle mapping, using recursion, breadth first and depth first
The turtle mapping, using recursion, breadth first and depth first

Time:02-24

Turtles library itself brought some demo, one example is using a recursive painting a tree, using breadth-first strategy, I will be slightly adapted in the following maketree2 function, in addition I also wrote a depth first version maketree1, however when testing the situation drives me crazy, maketree1 is always less than maketree2 draw a layer, the last time the test is in every layer of painting in the pen and write the serial number at the top, it's still found maketree1 in labeling after the last layer not drawing, please help solve,

The from turtle import *

# depth-first version
# ltur: the left branch of the turtle, length, branch length, Angle, left and right branch deflection Angle, thewire: the next layer length ratio, lenlimit: shortest length limit
Def maketree1 (ltur, length, Angle, thewire, lenlimit=3) :
Global count, layer # test
If length> Lenlimit:
Layer +=1 # test
Print (layer, length)
Turlist=[ltur]
Rtur=ltur. Clone ()
Ltur. Write (STR) (layer) # test
Ltur. Lt (Angle)
Rtur. Rt (Angle)
Ltur. Fd (length) # draw branches around
Rtur. Fd (length)
Turlist. Append (rtur)
# count +=2
# print (count)
For t in turlist:
* thewire maketree1 (t, length, Angle, thewire, lenlimit)
# the count -=1
# print (count)
Layer -=1


# breadth-first version
# lastlist: this layer all branch list
# currentlist: all branches of the next layer is drawing
Def maketree2 (lastlist, length, Angle, thewire, lenlimit=3) :
Global count, layer
If length> Lenlimit:
Layer +=1
Print (layer, length)
Currentlist=[]
For ltur lastlist in:
Ltur. Write (STR) (layer)
Ltur. Fd (length) draw the current branch #
Rtur=ltur. Clone ()
Ltur. Lt (Angle)
Rtur. Rt (Angle)
Currentlist. Append (ltur)
Currentlist. Append (rtur)
# count +=2
# print (count)
Maketree2 (currentlist, length * thewire, Angle, thewire, lenlimit)
Layer -=1
# the count -=len (currentlist)
# print (count)


Def the main () :
Global count, layer
The count=0
Firstlen=200
Angle=65
Thewire=0.6375
Lenlimit=60
T=Turtle ()
# t.s etundobuffer (None)
Todd Harper (t)
T.l t (90)
T.u p ()
T.b k (firstlen)
T.d own ()
# tracer (36, 0)
Tracer (False)
# depth-first test
Layer=1
T.f d (firstlen)
Maketree1 (t, firstlen * thewire, Angle, thewire, lenlimit)
# breadth-first test
# layer=0
# maketree2 ([t], firstlen, Angle, thewire, lenlimit)
Print (' time 'time. Process_time ())
Return the 'ok'


If __name__=="__main__ ':
Print (the main ())
Mainloop ()
  • Related