乱走乌龟功能不做我想做的事

2024-09-28 21:51:31 发布

您现在位置: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的回答,因为它最容易与我已经编程的内容联系起来,并在其他方面给了我一些建议,但布莱恩的回答也非常有用,如果可能的话,我会接受这两个答案。非常感谢你们俩!在


Tags: orimport屏幕defcounterrandomwindowturtle
3条回答

你的while循环是失败的原因,你知道。因此,您可以做的是使while循环只检查计数器,而不将isnscreen()作为while循环的一部分。现在为了检查你是否可以前进,你可以在跳跃前看,也就是说,在你当前的位置上加上50的值,看看你是否会在屏幕上,如果不前进,否则尽可能靠近,增加碰撞计数器,然后掉头。或者,Sukrit karla的答案可能更容易实现。在

作为嵌套循环的替代方法并避免一些冗余语句,下面的结果应该与Sukrit的答案相同。在

def randomWalk(t,w):
    counter = 0

    while counter < 4:
        if not isInScreen(w,t):
            t.left(180)
            counter += 1
        else:
            coin = random.randrange(0,2)
            if coin == 0:
                t.left(90)
            else:
                t.right(90)
        t.forward(50)

核心问题是确保isInScreen返回false不会导致while循环终止,同时在循环体中增加counter。在

您的counter = counter + 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()

如果{cd6>

相关问题 更多 >