如何使用列表检查海龟是否靠近邮票

2024-10-01 07:50:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如果海龟接近列表中的坐标(如下所示),我希望代码为python中的游戏返回一个True语句。在我的游戏中,邮票是在整个游戏过程中必须收集的硬币。游戏中的列表有10000个坐标,所以如果你对如何制作硬币收集系统有更好的想法,请告诉我

list_of_coords=[(150.0, -150.0),(50.0, -10.0),(-150.0, 0.0)]

非常感谢


Tags: of代码true游戏列表过程系统硬币
2条回答

要做到这一点,你可以使用两点之间的欧几里德距离(在2D中基本上简化为毕达哥拉定理)

假设您有这样的海龟坐标(与您提供的坐标样本格式相同,例如(X,Y)像素):

    turtle_coords = (10.0, 10.0)

您可以编写一个函数来计算海龟与任何其他点之间的距离(也可以使用numpy包中的sqrt函数)。此函数将海龟坐标(海龟坐标)视为一对(X海龟,Y海龟),将任何关注点坐标(点坐标)视为一对(X海龟,Y海龟)。在这些对中,您可以使用对[0]访问每个X值,使用对[1]访问每个Y值。距离函数如下所示:

    def distance(turtle_coords, point_coords):
        return ((turtle_coords[0] - point_coords[0])**2 + (turtle_coords[1] - point_coords[1])**2)**0.5

然后,您可以循环使用list_of_coords变量的所有坐标,以便创建海龟与每个感兴趣点之间的距离列表

    distances = []
    for point_coords in list_of_coords:
        distances.append(distance(turtle_coords, point_coords))

然后,您就有了一个所提供的每个坐标和海龟坐标之间的距离列表。然后,您可以评估海龟是否足够接近某些坐标。假设您有一个距离阈值:

    distance_threshold = 10   # Say 10 pixels
    close_to_coords = []
    for distance in distances:
        close_to_coords.append(distance <= distance_threshold)
        # You get a list like [False, False, True, False , etc...]

您可以尝试以下方法:

list_of_coords = [(150.0, -150.0), (50.0, -10.0), (-150.0, 0.0)]

def close_to_coord(coord):
    return turtle.distance(coord) < 10

if any(map(close_to_coord, list_of_coords)):
    # ...

由于andmap是惰性计算的,因此一旦找到一个接近的list_of_coords就应该停止处理

相关问题 更多 >