利用Python畫小樹和森林(寬度優先繪製+深度優先繪製)
阿新 • • 發佈:2019-02-18
在中M上看嵩天老師的《Python語言程式設計》時,視訊中給出了寬度優先繪製法的程式碼,僅提了一下還有另外一種畫法(深度優先繪製法).聯絡到最近學的資料結構,摸索出了另一種畫法。
原始碼:
''' Created on Dec 2, 2017 @author: QiZhao ''' # drawtree.py from turtle import Turtle 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) def tree2(p,l,a,f): #深度優先繪製法 if l>5: p.forward(l) q=p.clone() p.left(a) q.right(a) tree2(p, l*f, a, f) tree2(q, l*f, a, f) def maketree(x,y): p = Turtle() p.color("blue") p.pensize(5) p.setundobuffer(None) p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, #because hiding the turtle speeds up the drawing observably. #p.speed(9) p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on. #TurtleScreen methods can then be called for that object. p.left(90)# Turn turtle left by angle units. direction p.penup() #Pull the pen up – no drawing when moving. p.goto(x,y)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation. p.pendown()# Pull the pen down – drawing when moving. #這三條語句是一個組合相當於先把筆收起來再移動到指定位置,再把筆放下開始畫.否則turtle一移動就會自動的把線畫出來 tree([p], 100, 65, 0.6375) p.penup() p.setheading(90)#Set the orientation of the turtle to to_angle. p.goto(x,y) p.down() p.color("green") tree2(p, 100, 65, 0.6375) def main(): maketree(-200, -200) maketree(0, 0) maketree(200,-200) main()
效果圖: