TurtleGraphics Python:从墙上弹起乌龟? [英] TurtleGraphics Python: Bouncing turtle off the walls?
问题描述
所以,我正在尝试制作一个逼真的弹跳函数,其中海龟撞到墙壁并以相应的角度弹开.我的代码如下所示:
So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:
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()))
所以,这适用于侧壁,但我不知道如何让它从顶部/底部正确反弹.有什么建议吗?
So, this works for the side walls, but I don't get how to make it bounce correctly off the top/bottom. Any suggestions?
推荐答案
试试这个:
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.但是水平翻转和垂直翻转的数学有点不同.
My python syntax is a little rusty, sorry :P. But the math is a little different for a horizontal vs. a vertical flip.
编辑:
我怀疑发生的事情是您的乌龟正处于向上指向并卡在顶壁上方的情况.这将导致它无限期地翻转.您可以尝试添加以下条件:
I suspect that what is happening is your turtle is getting into a situation where it is pointing upwards and stuck above the top wall. That would lead it to just flip indefinitely. You could try adding the following conditions:
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 之间的值 - 如果不是,那么正确处理会更加棘手.
If that works, there is probably a bug elsewhere in your code. Edge handling is tricky to get right. I assume that turtle.heading() will always return something between 0 and 360 - if not then it will be even more tricky to get right.
这篇关于TurtleGraphics Python:从墙上弹起乌龟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!