Python TurtleGraphics - 如何平滑随机行走?

2 投票
3 回答
1599 浏览
提问于 2025-04-15 14:27

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

在tipsy_turtle()这个函数里,有一个小细节就是,当海龟转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)

但是效果并不好,我也不知道自己哪里出错了。谢谢!

3 个回答

0

我想我可以试着回答一下,虽然我不太确定你具体想要什么(可以看看我对问题的评论,如果需要,我会适时修改这个回答!)。

假设你想让海龟在每一步转动一定的角度,不一定是90度,但也不能超过90度,那么你只需要用 rand_num = random.randint(-90, 90) 这行代码来生成一个随机数,然后用 turtle.right(rand_num) 让海龟向右转动这个随机的角度。

0

你可能不需要考虑左转和右转的条件。因为我对Python的语法不太熟悉,所以我这里用伪代码来说明。

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

也就是说,先生成一个随机的角度,然后向左转这个角度,再生成另一个随机角度,向右转这个角度。这样你就不用担心生成负数的随机数了。你可以保持所有的随机角度都是正数,而先左转再右转的组合,实际上就相当于帮你做了减法,这样可以让方向变化的分布更均匀。

2

希望这个例子能帮助你理解你之前的代码出了什么问题——你要么进行了 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)

或者你可以这样写:

for step in xrange(90):
    if rand_num < 0:
        turtle.left(rand_num)
    else:
        turtle.right(rand_num)

对于这样的代码,实际上只是个人喜好问题。

撰写回答