2012-10-09 212 views
3

我想寫一個程序使用python的龜創建一個層級的樹。下面是一些I/O,所以你可以看到它是做什麼的。Python Turtle遞歸樹

enter image description here

我的程序適用於第一種情況,但打印太多的第二種情況。該方案的規定是:

  • 必須是遞歸

  • 只能使用下面的龜功能:

    turtle.forward(100)  <-- turtle goes forward 100 steps 
    turtle.right(90)  <-- turtle turns right 90 degrees 
    turtle.penup()   <-- turtle lifts its pen up off of the paper 
    turtle.forward(100)  <-- turtle goes forward 100 steps 
    turtle.pendown()  <-- turtle puts its pen down on the paper 
    turtle.pencolor("red") <-- turtle uses red pen 
    turtle.circle(100)  <-- turtle draws circle of radius 100 
    turtle.pencolor("blue") <-- turtle changes to blue pen (most other common colors work too!) 
    turtle.forward(50)  <-- turtle moves forward 50 steps 
    turtle.xcor()   <-- turtle returns its current x-coordinate 
    turtle.ycor()   <-- turtle returns its current y-coordinate 
    

我的計劃:

import turtle 

def tree(length,n): 
    """ paints a branch of a tree with 2 smaller branches, like an Y""" 
    if length < (length/n): 
      return  # escape the function 
    turtle.forward(length)  # paint the thik branch of the tree 
    turtle.left(45)   # rotate left for smaller "fork" branch 
    tree(length * 0.5,length/n)  # create a smaller branch with 1/2 the lenght of the parent branch 
    turtle.right(90)   # rotoate right for smaller "fork" branch 
    tree(length * 0.5,length/n)  # create second smaller branch 
    turtle.left(45)   # rotate back to original heading 
    turtle.backward(length)  # move back to original position 
    return    # leave the function, continue with calling program 
+3

我不知道龜是建在蟒蛇。你已經完成了我的一天。 – BostonJohn

+0

很高興我可以:) – user1681664

回答

6

我認爲有t我的問題。

首先,對於遞歸調用,第二個參數應該是n-1而不是長度/ n。如果您正在繪製級別n,則下一次調用將繪製級別n-1,而不是級別長度/ n。

第二個問題是逃生條件。第一次更改時,繪圖將在沒有更多等級繪製時完成,或n == 1。

這聽起來像作業,所以我不會發布確切的代碼。

+0

非常感謝。 – user1681664