【发布时间】:2013-08-05 16:36:18
【问题描述】:
我必须编写一个程序,让乌龟在屏幕周围旋转 90 度,随机选择左或右,直到它撞到墙壁,旋转 180 度,然后回到屏幕周围行走。当它撞墙 4 次时,循环终止。我遇到的问题是,当它从墙上反弹时,它会停止行走,并且循环显然已经终止,因为我可以通过单击它来关闭窗口(@987654321@)。这是完整的程序:
import turtle
import random
def isInScreen(w,t):
leftBound = w.window_width() / -2
rightBound = w.window_width() / 2
bottomBound = w.window_height() / -2
topBound = w.window_height() / 2
turtlex = t.xcor()
turtley = t.ycor()
stillIn = True
if turtlex < leftBound or turtlex > rightBound or turtley < bottomBound or turtley > topBound:
stillIn = False
return(stillIn)
def randomWalk(t,w):
counter = 0
while isInScreen(w,t) and counter < 4:
coin = random.randrange(0,2)
if coin == 0:
t.left(90)
else:
t.right(90)
t.forward(50)
t.left(180)
t.forward(50)
counter = counter+1
wn = turtle.Screen()
wn.bgcolor('lightcyan')
steklovata = turtle.Turtle()
steklovata.color('darkslategray')
steklovata.shape('turtle')
randomWalk(steklovata,wn)
wn.exitonclick()
我对它为什么停止感到困惑,考虑到一旦乌龟反弹回来,它的 x 和 y 坐标满足 isInScreen(w,t) 为真的要求,因此又回到了行走状态。有什么想法吗?
编辑: 接受了 Sukrit 的回答,因为它最容易与我已经编程的内容联系起来,并在其他方面给了我一些指示,但 Brian 的回答非常也很有用,如果可能的话,我会接受两者。非常感谢你们!
【问题讨论】:
-
好的,看起来你的while循环在它离开屏幕的那一刻失败了,它反弹回来,是的,因为它在第一个while循环之外。如果您尝试在计数器
标签: python python-3.x turtle-graphics