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


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

我已经创建了一个上面提到的Python数组。它包含点的元组 (x,y)。我假设我从第一点开始(而不是原始点)。我想按给定的顺序移动到点。我唯一的移动功能是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]

好的,所以你的机器人正朝向某个已知的基本方向,并且位于某个已知位置,并且您希望它移动到另一个位置。

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

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

因此,面向方向0时移动意味着您的 x 坐标增加每单位时间 1 个,您的 y 坐标保持不变,依此类推。这方向是介于 0 到 3 之间的整数(包括 0 和 3)。

现在代码需要弄清楚如何继续。我会从任何开始机器人当前面向的方向。假设所需的位移是 (-2, 1)dir0. atod[dir] (1, 0).忽略那个这是零;将-2除以1,得到-2,所以这个方向是不好,我们必须轮换。哪条路?检查每个,看看哪种方式帮助。如果这两种方法都没有帮助,你需要做一个180,无论哪个都做你喜欢的方向。

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

您可以沿北/南或东/西轴移动,因为您的旋转限制为 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 度旋转。

最新更新