为了账号安全,请及时绑定邮箱和手机立即绑定

当一只正在移动的 Python 乌龟靠近另一只乌龟时停止它

当一只正在移动的 Python 乌龟靠近另一只乌龟时停止它

胡子哥哥 2021-08-14 17:12:39
while当另一只乌龟有 50 个单位时,如何使用循环停止随机移动的乌龟?我有一只乌龟随机选择一个位置并创建一个大点或洞,另一只乌龟随机移动 90 度转弯并每次向前移动 50 个单位。随机移动的乌龟在离开屏幕末端时停止,但是当乌龟到达另一只乌龟创建的洞时,我如何也让乌龟停止?import randomimport turtledef turtlesClose(t1, t2):    if t1.distance(t2)<50:        return True    else:        return Falsedef isInScreen(win,turt):    leftBound = -win.window_width() / 2    rightBound = win.window_width() / 2    topBound = win.window_height() / 2    bottomBound = -win.window_height() / 2    turtleX = turt.xcor()    turtleY = turt.ycor()    stillIn = True    if turtleX > rightBound or turtleX < leftBound:        stillIn = False    if turtleY > topBound or turtleY < bottomBound:        stillIn = False    return stillIndef main():    wn = turtle.Screen()    # Define your turtles here    june = turtle.Turtle()    july = turtle.Turtle()    july.shape('turtle')    july.up()    july.goto(random.randrange(-250, 250, 1), random.randrange(-250, 250, 1))    july.down()    july.dot(100)    june.shape('turtle')    while isInScreen(wn,june):        coin = random.randrange(0, 2)        dist = turtlesClose(july, june)        if coin == 0:            june.left(90)        else:            june.right(90)        june.forward(50)        if dist == 'True':            breakmain()
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

您的代码的问题是以下语句:


if dist == 'True':

你不想要引号周围True。虽然这会起作用:


if dist == True:

正确的表达方式是:


if dist is True:

或者更好:


if dist:

否则你的代码似乎工作。下面是利用一些海龟习语和其他代码清理的重写:


from random import randrange, choice

from turtle import Screen, Turtle


CURSOR_SIZE = 20


def turtlesClose(t1, t2):

    return t1.distance(t2) < 50


def isInScreen(window, turtle):

    leftBound = -window.window_width() / 2

    rightBound = window.window_width() / 2

    topBound = window.window_height() / 2

    bottomBound = -window.window_height() / 2


    turtleX, turtleY = turtle.position()


    return leftBound < turtleX < rightBound and bottomBound < turtleY < topBound


def main():

    screen = Screen()


    july = Turtle('circle')

    july.shapesize(100 / CURSOR_SIZE)


    july.up()

    july.goto(randrange(-250, 250), randrange(-250, 250))

    july.down()


    june = Turtle('turtle')


    while isInScreen(screen, june):


        if turtlesClose(july, june):

            break


        turn = choice([june.left, june.right])


        turn(90)


        june.forward(50)


main()


查看完整回答
反对 回复 2021-08-14
  • 1 回答
  • 0 关注
  • 234 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信