python – 随意行走龟功能不做我想要的
作者:互联网
我必须编写一个程序,其中一只乌龟需要90度转弯,在屏幕周围随机选择左右,直到它撞到墙壁,转180度然后回到屏幕上走动.当它撞到墙壁4次时,循环终止.我遇到的问题是当它从墙上反弹时它就会停止行走,并且循环已经明显终止,因为我可以通过点击它来关闭窗口(wn.exitonclick).这是完整的程序:
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的答案也非常有用,如果有可能的话,我会接受.非常感谢你们俩!
解决方法:
你的柜台=柜台1是错的.当您的isInScreen返回False时,while循环中断并且代码结束,因为,计数器正在递增,但您不会再次循环.请参阅以下代码 –
import turtle
import random
def isInScreen(w,t):
leftBound = w.window_width() / -2.0
rightBound = w.window_width() / 2.0
bottomBound = w.window_height() / -2.0
topBound = w.window_height() / 2.0
turtlex = t.xcor()
turtley = t.ycor()
if turtlex < leftBound or turtlex > rightBound or turtley < bottomBound or turtley > topBound:
return False
return True
def randomWalk(t,w):
counter = 0
while True:
while isInScreen(w,t):
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 += 1
if counter == 4:
break
wn = turtle.Screen()
wn.bgcolor('lightcyan')
steklovata = turtle.Turtle()
steklovata.color('darkslategray')
steklovata.shape('turtle')
randomWalk(steklovata,wn)
wn.exitonclick()
P.S – 您不需要变量来存储stillIn,如果if条件的计算结果为True,则返回False,如果它不返回True. (上述代码中反映的变化).
标签:turtle-graphics,python,python-3-x 来源: https://codeday.me/bug/20190831/1777283.html