TurtleGraphics Python:从墙上弹起乌龟?
所以,我试图制作一个真实的弹跳功能,海龟撞到墙壁并以相应的角度弹开。我的代码如下所示:
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, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这样的事情:
我的 python 语法有点生疏,抱歉:P。但水平翻转和垂直翻转的数学计算略有不同。
编辑:
我怀疑发生的情况是你的乌龟陷入了一种指向上方并卡在顶墙上方的情况。这将导致它无限期地翻转。您可以尝试添加以下条件:
如果有效,则代码中的其他位置可能存在错误。边缘处理很难正确处理。我假设turtle.heading()总是会返回0到360之间的值——如果不是,那么正确的结果会更加棘手。
Try something like this:
My python syntax is a little rusty, sorry :P. But the math is a little different for a horizontal vs. a vertical flip.
EDIT:
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 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.
天呐,
你的问题似乎是你使用相同的三角函数来计算右墙和左墙,就像你是顶部和底部一样。一张纸和一支铅笔就足以计算所需的挠度。
我使用了 setheading 函数和辅助函数 (inbounds) 来进一步声明此处代码的意图。在您编写的任何代码中提供某种文档字符串也是一种很好的做法(前提是它所声明的消息是准确的!!)
您的情况可能会因使用
xrange
而有所不同,Python 3.0+ 会对其进行重命名简单地范围
。Gday,
Your problem seems to be that you are using the same trigonometry to calculate the right and left walls, as you are the top and bottom. A piece of paper and a pencil should suffice to calculate the required deflections.
I've used the
setheading
function and a helper function (inbounds
) to further declare the intent of the code here. Providing some kind of doc-string is also good practice in any code that you write (provided the message it states is accurate!!)Your mileage may vary on the use of
xrange
, Python 3.0+ renames it to simplyrange
.