TurtleGraphics Python:从墙上弹起乌龟?

2023-12-19

所以,我试图制作一个真实的弹跳功能,海龟撞到墙壁并以相应的角度弹开。我的代码如下所示:

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。但水平翻转和垂直翻转的数学计算略有不同。

EDIT:

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

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之间的值——如果不是,那么正确的结果会更加棘手。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TurtleGraphics Python:从墙上弹起乌龟? 的相关文章

随机推荐