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

while当另一只乌龟有 50 个单位时,如何使用循环停止随机移动的乌龟?


我有一只乌龟随机选择一个位置并创建一个大点或洞,另一只乌龟随机移动 90 度转弯并每次向前移动 50 个单位。随机移动的乌龟在离开屏幕末端时停止,但是当乌龟到达另一只乌龟创建的洞时,我如何也让乌龟停止?


import random

import turtle


def turtlesClose(t1, t2):

    if t1.distance(t2)<50:

        return True

    else:

        return False


def 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 stillIn


def 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':

            break


main()


胡子哥哥
浏览 235回答 1
1回答

鸿蒙传说

您的代码的问题是以下语句:if dist == 'True':你不想要引号周围True。虽然这会起作用:if dist == True:正确的表达方式是:if dist is True:或者更好:if dist:否则你的代码似乎工作。下面是利用一些海龟习语和其他代码清理的重写:from random import randrange, choicefrom turtle import Screen, TurtleCURSOR_SIZE = 20def turtlesClose(t1, t2):&nbsp; &nbsp; return t1.distance(t2) < 50def isInScreen(window, turtle):&nbsp; &nbsp; leftBound = -window.window_width() / 2&nbsp; &nbsp; rightBound = window.window_width() / 2&nbsp; &nbsp; topBound = window.window_height() / 2&nbsp; &nbsp; bottomBound = -window.window_height() / 2&nbsp; &nbsp; turtleX, turtleY = turtle.position()&nbsp; &nbsp; return leftBound < turtleX < rightBound and bottomBound < turtleY < topBounddef main():&nbsp; &nbsp; screen = Screen()&nbsp; &nbsp; july = Turtle('circle')&nbsp; &nbsp; july.shapesize(100 / CURSOR_SIZE)&nbsp; &nbsp; july.up()&nbsp; &nbsp; july.goto(randrange(-250, 250), randrange(-250, 250))&nbsp; &nbsp; july.down()&nbsp; &nbsp; june = Turtle('turtle')&nbsp; &nbsp; while isInScreen(screen, june):&nbsp; &nbsp; &nbsp; &nbsp; if turtlesClose(july, june):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; turn = choice([june.left, june.right])&nbsp; &nbsp; &nbsp; &nbsp; turn(90)&nbsp; &nbsp; &nbsp; &nbsp; june.forward(50)main()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python