Python TurtleGraphics-平滑随机游动?

Python TurtleGraphics-平滑随机游动?,python,Python,我需要一些关于Python中TurtleGraphics的问题的帮助: 醉鬼乌龟()的一个小细节是,当乌龟转90度时,它会立即“跳”到新的方向。这使得它的运动看起来参差不齐。如果乌龟在转弯时动作平稳,看起来会更好。因此,对于这个问题,编写一个名为smooth_tipsy_turtle()的函数,该函数与tipsy_turtle()相同,只是不使用turtle.right(d)函数,而是编写一个名为smooth_right(d)的全新函数,其工作原理如下: - If d is negative

我需要一些关于Python中TurtleGraphics的问题的帮助:

醉鬼乌龟()的一个小细节是,当乌龟转90度时,它会立即“跳”到新的方向。这使得它的运动看起来参差不齐。如果乌龟在转弯时动作平稳,看起来会更好。因此,对于这个问题,编写一个名为smooth_tipsy_turtle()的函数,该函数与tipsy_turtle()相同,只是不使用turtle.right(d)函数,而是编写一个名为smooth_right(d)的全新函数,其工作原理如下:

 - If d is negative then
      - repeat the following -d times:
            - turn left 1 using the ordinary turtle.left command

  - Otherwise, repeat the following d times:
          - turn right 1 using the ordinary turtle.right command
下面是我的原始函数,用于获取海龟的随机运动:

def tipsy_turtle(num_steps):
    turtle.reset()
    for step in range(num_steps):
       rand_num = random.randint(-1, 1)
       turtle.right(rand_num * 90)
       turtle.forward(5 * random.randint(1, 3))
那么,我该怎么做才能让它成功呢?我试着加上:

   if rand_num*90 < 0:
       for step in range(rand_num*90):
           turtle.left(rand_num*90)
   else:
       turtle.right(rand_num*90)
如果rand_num*90<0:
对于步进范围(rand_num*90):
海龟。左(兰特数*90)
其他:
海龟。右(兰特数*90)

但它并没有真正起作用,我不知道我做错了什么。谢谢

希望此示例能够澄清您示例中的错误——您执行了
rand_num*90*rand_num*90
左转或
rand_num*90
右转

if rand_num < 0: # don't need to multiply by 90 here - it's either +ve or -ve.
    for step in xrange(90): # xrange is preferred over range in situations like this
         turtle.left(rand_num) # net result is 90 left turns in rand_num direction
else:
    for step in xrange(90):
         turtle.right(rand_num)
如果rand_num<0:#这里不需要乘以90-它是+ve或-ve。
对于xrange(90)中的步骤:#在这种情况下,xrange优先于range
海龟。左(rand_num)#净结果是在rand_num方向左转90圈
其他:
对于X范围(90)中的步长:
海龟。对(兰特数量)
或者你可以这样写:

for step in xrange(90):
    if rand_num < 0:
        turtle.left(rand_num)
    else:
        turtle.right(rand_num)
xrange(90)中步进的
:
如果rand_num<0:
乌龟。左(兰特)
其他:
海龟。对(兰特数量)

对于这样的代码,这实际上是一个偏好的问题。

您可能不需要条件For left vs right。我没有python语法,所以这里是伪代码

turtle left randomly generated value 0 to 90
turtle right randomly generated value 0 to 90
turtle forward some amount

也就是说,生成一个随机角度并向左拐那么多,然后生成另一个随机角度并向右拐那么多。这样,您就不必担心生成或处理负随机数。你可以保持所有的随机角度为正,左跟右的组合有效地为你做了一个减法,这给了方向变化一个很好的高斯分布

我想我会大胆地给出一个答案,即使我不完全确定你想要什么(请参阅我对问题的评论,如果我适当地编辑这个答案,请不要感到惊讶!)


假设你想让乌龟在每一步转动一定的度数,不一定是90度,但不超过90度,那么只需使用
rand\u num=random.randint(-90,90)
,然后使用
turtle.right(rand\u num)

对不起,我不完全清楚你想要什么。你想让乌龟在前进之前旋转一些随机数度(最多90度),还是只想乌龟在改变方向时“明显旋转”,但在移动之前仍然以90度增量旋转?另外,您使用的是什么版本的Python?海龟模块在2.6版本中得到了显著的升级。实际上,如果rand_num可以是正的或负的,那么你只需要右转。(或仅左转。)turtle.right(-1)的行为与turtle.left(1)的行为相同。至少在我使用的turtle模块(Windows上的Python 2.6.1)中,处理负随机数并不比选择左或右更难。正如我在对马克·拉沙科夫的回答的评论中所指出的,右转负的数量相当于左转正的数量。Python的随机数功能使得总是选择一个方向并允许负角度变得更加简单。。我只是想让大家知道,有其他选择可以从=)