2016-04-24 51 views
0

當我導入烏龜,然後嘗試使用while True:循環,它不起作用。這裏的代碼:雖然:不與龜一起工作

import turtle 
import time 

stage = turtle.Turtle() 

width = 900 
height = 500 

def up(): 
    turtle.setheading(90) 
    turtle.forward(10) 

def down(): 
    turtle.setheading(270) 
    turtle.forward(10) 

def char(): 
    turtle.listen() 
    turtle.onkey(up, 'w') 
    turtle.onkey(up, 's') 

turtle.setup(width, height) 
turtle.goto(390, 0) 
char() 

while True: 
    if (turtle.ycor() >= 250): 
     turtle.goto(460, 0) 

stage.goto(350, 0) 
turtle.done() 

我不知道爲什麼它不工作,它只是凍結(沒有響應),然後,沒有錯誤信息。這真的很煩人,因爲同樣的事情發生在其他程序,我有烏龜,而真正的循環。

如果當真是問題時,有沒有其他方法可以'永久檢查',謝謝!

+1

你在哪裏完成'while'循環? –

+0

當'turtle'在'(390,0)'時,爲什麼你會期望'turtle.ycor()> = 250',即當它的y座標等於零? –

+0

因爲你上下移動烏龜,但是我不能,因爲窗口沒有響應,你用W和S移動它,當它碰到頂部時,它會回落 –

回答

0

而不是你的無限循環,你可以有移動龜檢查任何常規若龜已達到感興趣的邊界:

import turtle 

WIDTH = 900 
HEIGHT = 500 

def up(): 
    turtle.setheading(90) 
    turtle.forward(10) 
    check() 

def down(): 
    turtle.setheading(270) 
    turtle.forward(10) 
    check() 

def check(): 
    if turtle.ycor() >= HEIGHT/2: 
     turtle.goto(400, 0) 

turtle.setup(WIDTH, HEIGHT) 

turtle.goto(350, 0) 

turtle.listen() 
turtle.onkey(up, 'w') 
turtle.onkey(down, 's') 

turtle.done() 

另外請注意,您的原始代碼有兩隻烏龜,默認的和一個叫做stage的人 - 確保跟蹤你操縱的烏龜!此外,坐在你的座標系之上,你將烏龜從屏幕上移開(除非這是你想要的),無法將其移回屏幕上。

0

我不知道你要完成什麼,但你很可能只是把

if (turtle.ycor() >= 250): 
    turtle.goto(460, 0) 

內部向上()和向下()。

雖然如果您需要永久運行該功能,正如您在評論中提到的那樣,您可以將第while True:件事放入第二個線程中,以防止窗口凍結。