gpt4 book ai didi

python - TurtleGraphics Python : Bouncing turtle off the walls?

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

所以,我正在尝试制作一个逼真的弹跳功能, turtle 撞到墙壁并以相应的角度弹开。我的代码如下所示:

def bounce(num_steps, step_size, initial_heading):
turtle.reset()
top = turtle.window_height()/2
bottom = -top
right = turtle.window_width()/2
left = -right

turtle.left(initial_heading)
for step in range(num_steps):
turtle.forward(step_size)
x, y = turtle.position()
if left <= x <= right and bottom <= y <= top:
pass
else:
turtle.left(180-2 * (turtle.heading()))

所以,这适用于侧壁,但我不知道如何让它从顶部/底部正确弹起。有什么建议吗?

最佳答案

尝试这样的事情:

if not (left <= x <= right):
turtle.left(180 - 2 * turtle.heading())
elif not (bottom <= y <= top):
turtle.left(-2 * turtle.heading())
else:
pass

我的 python 语法有点生疏,抱歉:P。但水平翻转和垂直翻转的数学计算略有不同。

编辑:

我怀疑发生的情况是你的 turtle 陷入了一种指向上方并卡在顶墙上方的情况。这将导致它无限期地翻转。您可以尝试添加以下条件:

if (x <= left and 90 <= turtle.heading() <= 270) or (right <= x and not 90 <= turtle.heading() <= 270):
turtle.left(180 - 2 * turtle.heading())
elif (y <= bottom and turtle.heading() >= 180) or (top <= y and turtle.heading <= 180):
turtle.left(-2 * turtle.heading())
else:
pass

如果有效,则您的代码中其他地方可能存在错误。边缘处理很难正确处理。我假设 Turtle.heading() 总是会返回 0 到 360 之间的值 - 如果不是,那么正确的结果会更加棘手。

关于python - TurtleGraphics Python : Bouncing turtle off the walls?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1457332/

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