Python - 旋转/移动指令的坐标

时间:2016-02-22 22:13:31

标签: python myro

coordinates = [(0, 2), (0, 1), (1, 2), (1, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]

我已经创建了一个上面提到的Python数组。它包含点元组(x,y)。我假设我从第一点开始(不是orgin)。我想按顺序移动到这些点。我唯一的移动函数是rotate90Degrees(direction),其中方向是1或-1分别为左和右。 forward(time)时间是移动的时间。我假设时间= 1相当于坐标系中的一个单位。是否有一种聪明的方法可以轻松地将其更改为移动指令而没有巨大的if / else if / else?到目前为止我所拥有的:

start = coordinates[0]
for x in range(1,len(coordinates)):
    finish = coordinates[x]
    change.append((finish[0] - start[0],finish[1] - start[1]))
    start = coordinates[x]

2 个答案:

答案 0 :(得分:0)

好的,所以你的机器人面向一些已知的主要方向,并且正在 一些已知位置,您希望它移动到另一个位置。

首先,您需要一个将方向映射到位移的元组列表。 我将使用标准单位圆,角度为90的倍数 度:

atod = [(1, 0), (0, 1), (-1, 0), (0, -1)]

面向方向0时移动意味着x坐标增加 每单位时间减1,你的y坐标不变,依此类推。该 方向是从0到3的整数。

现在代码需要弄清楚如何继续。我从任何事情开始 机器人目前面临的方向。说所需的位移是 (-2, 1)dir0atod[dir](1, 0)。忽略那一个 那是零;将-2除以1,然后得到-2,这样就可以了 没有好处,我们必须轮换。哪一条路?检查每一个,看哪个方向 帮助。如果两种方式都没有帮助,你需要做180,做任何一个 你喜欢的方向。

所以我们进行了轮换,现在我们处于方向1atod[dir] (0, 1)。所以我们希望通过1前进。这样做。现在你必须 再次旋转,再次移动,你就完成了。

答案 1 :(得分:0)

您可以沿着北/南或东/西轴移动,因为您的旋转限制在90度。

您可以观察到任何移动都有一个北/南组件和一个东/西组件。

如果你的动作一致,那么你离下一步只有90度转角:

1. turn east or west
2. move east or west
3. turn north or south
4. move north or south
5. You should be at your target
6. turn east or west
7. move east or west
8. turn north or south
9. move north or south
10. you should be at your (next) target

......等等。

如果我们假设您的机器人朝向北方开始,那么您的环路应首先转向东/西,然后移动,然后转向北/向。

这是一个开始。这可能是您的全球数据和主要代码。

Robot_pos = coordinates[0]
Robot_facing = NORTH

for next_pos in coordinates[1:]:
    move_robot(next_pos)

如果我们假设x是东/西,y是北/南,那么你对move_robot有类似的东西:

def move_robot(new_pos):
    """
    Move robot from ``Robot_pos`` to ``new_pos`` given. The robot
    is assumed to be facing either north or south upon entry, so
    east/west movement is done first.
    """

    delta_x = ...
    turn_robot(EAST or WEST)
    forward( some amount )

    # similarly for Y

您必须在turn_robot()代码中稍微聪明一点才能优化轮次,无论您是从正面还是负面开始。但它应始终是一个90度旋转。