2015-10-23 21 views
2

爲了與龜使用遞歸得出這樣的:Python的遞歸函數龜,吸引資本我的

https://gyazo.com/4a6d64fd83c1dbf894914bb91c8189b1

但我真的不擅長這個。這就是我得到:

https://gyazo.com/ec6ffa37b1792ed08b9260f4e496a953

下面的代碼: https://gyazo.com/24cebddbb111506fd6959bb91dadb481

import turtle 
def draw_shape(t, level,size): 
    if level == 1: #draws an I 
     t.down() 
     t.forward(size/2) 
     t.left(90) 
     t.forward(size/2) 
     t.back(size) 
     t.forward(size/2) 
     t.left(90) 
     t.forward(size) 
     t.left(90) 
     t.forward(size/2) 
     t.back(size) 
     t.up() 
     t.forward(size/2) 
     t.left(90) 
     t.forward(size/2) 

    else: 
     draw_shape(t,level - 1,size) 
     t.back(size/2) 
     t.right(90) 
     t.forward(size/2) 
     t.left(90) 
     draw_shape(t,level - 1,size/2) 
     t.left(90) 
     t.forward(size) 
     t.right(90) 
     draw_shape(t,level-1,size/2) 
     t.right(90) 
     t.forward(size/2) 
     t.left(90) 
     t.forward(size) 
     t.right(90) 
     t.forward(size/2) 
     t.left(90) 
     draw_shape(t,level-1,size/2) 
     t.left(90) 
     t.forward(size) 
     t.right(90) 
     draw_shape(t,level-1,size/2) 

def q1(): 
    my_win = turtle.Screen() 
    my_turtle = turtle.Turtle() 
    my_turtle.speed(0.006) 
    my_turtle.left(90) 
    my_turtle.up() 
    my_turtle.back(200) 
    n = int(input('Draw shape at level: ')) 
    draw_shape(my_turtle,n,200) 
    my_win.exitonclick() 

q1() 

差不多隻是爲了編輯draw_shape()函數。我在第2級正確地做到了,但其餘的關卡開始變得亂七八糟,並且在錯誤的位置上繪製了錯誤的大小,我認爲這是因爲我在繪製完成後放置了指針。任何幫助將不勝感激。

+0

你可以在問題中添加代碼作爲文本嗎?我們無法複製和粘貼屏幕截圖。 – Blckknght

+0

不知道如何感謝溢出,但感謝您幫助我的第一篇文章,你爲我節省了很多頭髮,因爲我不知道如何在每次打電話後讓筆回到中心。絕對需要經過幾次才能得到遞歸的結果。再次感謝我真的很感激它:) – thecylax

回答

1

我發現你的代碼有兩個問題,就像你現在使用的那樣。

第一種情況是,代碼的下半部分在完成後不會將龜放回中心點。這就是爲什麼較小的棋子會在各種隨機位置上畫出來的原因,因爲之前的調用使得烏龜離開了某個奇怪的地方。

第二個問題是您在開始時使用遞歸調用權。這並不是必須的,因爲無論如何你都會沿着I的形狀移動。

我會建議什麼使您的基本案例level < 1。這並不要求你做任何事情(你可以立即return)。這將取代您的整個if level == 1區塊(您需要保留的t.down()除外)。

def draw_shape(t, level, size): 
    if level < 1: # base case 
     return 

    t.down() # put pen down at the start, don't recurse immediately 
    t.back(size/2) 
    t.right(90) 
    t.forward(size/2) 
    t.left(90) 
    draw_shape(t, level - 1, size/2) 
    t.left(90) 
    t.forward(size) 
    t.right(90) 
    draw_shape(t, level - 1, size/2) 
    t.right(90) 
    t.forward(size/2) 
    t.left(90) 
    t.forward(size) 
    t.right(90) 
    t.forward(size/2) 
    t.left(90) 
    draw_shape(t, level - 1, size/2) 
    t.left(90) 
    t.forward(size) 
    t.right(90) 
    draw_shape(t, level - 1, size/2) 
    t.right(90)    # add lines below to get back to start position 
    t.forward(size/2) 
    t.left(90) 
    t.back(size/2) 

你也許可以拿起筆,並從我的一端跳到另一個略微簡化這一目的(例如從左下左上),而不是在中間欄繪製額外的時間。我保留了大部分代碼,使必要的更改(而不僅僅是更好)更清晰。