gpt4 book ai didi

Python turtle 在边界内随机游走

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:58 24 4
gpt4 key购买 nike

我想使用 turtle 创建一个程序,该程序在随机距离上沿随机方向移动 50 次,在 x 轴和 y 轴上保持在 -300 到 300 之间(通过向相反方向转动并在到达时向前移动)边界)。

当if语句为真时,代码运行正常,但偶尔执行else语句时(由于超出边界)else语句会反复执行,直到计数达到50。换句话说,它会倒退并沿着同一条线前进。我不明白为什么,因为当 turtle 弹开时,它应该在边界内并再次运行 if 语句,而不是 else 语句。我该如何解决这个问题,以便 turtle 在弹跳后继续随机行走?谢谢

我的代码如下所示

import turtle
import random

count = 0
while count <51:
count += 1
if (turtle.xcor() >-300 and turtle.xcor() <300) and\
(turtle.ycor() >-300 and turtle.ycor() <300):
turtle.forward(random.randint(30,100))
turtle.right(random.randint(0,360))
else:
turtle.right(180)
turtle.forward(300)

最佳答案

在if语句中,应该先转向,再前进:

假设您在 (0,299) 处, turtle 面朝上,您将向前(假设为 100),然后转弯(假设为向左)。然后您将位于 (0, 399),面向左侧。

然后你将进入 else 循环,向右/300,所以将在 300/399,所以仍然超出范围(注意 forward(300) 可能有点太太多了)。

如果先转弯,再往前走,就真的掉头了。
但再一次,300 可能太多了。我宁愿用类似的东西保存以前的距离:

if (-300 < turtle.xcor() <300) and (-300 < turtle.ycor() <300):
turtle.right(random.randint(0,360))
distance = random.randint(30,100)
turtle.forward(distance)
else:
turtle.right(180)
turtle.forward(distance)

假设您在 (299,299),转 135°(向上/向左),向前 100。然后您将得到 y>300,如果您掉头,然后向前300,你将得到 x>300。然后再次进入循环。

关于Python turtle 在边界内随机游走,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28113218/

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