当移动的Python乌龟靠近另一只乌龟时将其停止

时间:2018-11-11 04:25:33

标签: python python-3.x turtle-graphics

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

我有一只乌龟随机选择一个位置并创建一个大的点或洞,另一只乌龟随机移动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()

1 个答案:

答案 0 :(得分:0)

您的代码存在以下问题:

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()