Turtle Graphics Python:从墙上弹出乌龟?

时间:2009-09-21 23:04:29

标签: python turtle-graphics

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

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()))

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

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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。但是对于水平翻转和垂直翻转,数学有点不同。

修改

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

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之间的东西 - 如果没有,那么右转就会变得更加棘手。

答案 1 :(得分:0)

g·天,

您的问题似乎是您使用相同的三角法计算右侧和左侧墙壁,因为您是顶部和底部。一张纸和一支铅笔应该足以计算出所需的偏转。

def inbounds(limit, value):
    'returns boolean answer to question "is turtle position within my axis limits"'
    return -limit < value * 2 < limit

def bounce(num_steps, step_size, initial_heading):
    '''given the number of steps, the size of the steps 
        and an initial heading in degrees, plot the resultant course
        on a turtle window, taking into account elastic collisions 
        with window borders.
    '''

    turtle.reset()
    height = turtle.window_height()
    width = turtle.window_width()
    turtle.left(initial_heading)

    for step in xrange(num_steps):
        turtle.forward(step_size)
        x, y = turtle.position()

        if not inbounds(height, y):
            turtle.setheading(-turtle.heading())

        if not inbounds(width, x):
            turtle.setheading(180 - turtle.heading())

我已经使用setheading函数和辅助函数(inbounds)来进一步声明代码的意图。在你编写的任何代码中提供某种文档字符串也是一种很好的做法(前提是它所说的信息是准确的!!)

使用xrange时,您的里程可能会有所不同,Python 3.0+将其重命名为range