gpt4 book ai didi

python - 当一只正在移动的 Python turtle 靠近另一只 turtle 时,阻止它

转载 作者:太空宇宙 更新时间:2023-11-03 21:35:53 25 4
gpt4 key购买 nike

当一只随机移动的 turtle 与另一只 turtle 的 50 个单位一起出现时,如何使用 while 循环停止它?

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

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

最佳答案

您的代码的问题在于以下语句:

if dist == 'True':

您不需要在 True 周围加上引号。虽然这会起作用:

if dist == True:

正确的表达方式是:

if dist is True:

或者更好:

if dist:

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

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

关于python - 当一只正在移动的 Python turtle 靠近另一只 turtle 时,阻止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53245825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com