python中的数组搜索

2024-04-19 04:02:28 发布

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

我正在尝试代码的一个游戏,将处理碰撞检测部分。现在看起来像这样

def collision_detection(player_x, player_y):
movment_ok=1
cannot_go_onto=[[0,20,20,40],[520,500,480,460]] #coordinates with no access. X, Y
if player_x in cannot_go_onto[0]:
    location_in_array=cannot_go_onto[0].index(int(player_x))
    if player_y==cannot_go_onto[1][location_in_array]:
        print("collision detection")
        movment_ok=0
return movment_ok

这对坐标(0,520)(20,500)&;(40,460)很好,但对坐标(20,480)不起作用。我想这是因为排队

location_in_array=cannot_go_onto[0].index(int(player_x))

索引搜索返回1,因为它只需要20第一次出现在数组中两次。因此,只有位置(20,500)在数组中首先出现时才被检查。但是我不知道怎么解决这个问题。任何想法/帮助都将不胜感激。你知道吗


Tags: ingoindexifoklocation数组array
1条回答
网友
1楼 · 发布于 2024-04-19 04:02:28

仅仅有一个不可访问的坐标数组,而不是两个独立的列表,不是更简单吗。你知道吗

cannot_go_onto = set([(0,520), (20,500), (20,480), (40,460)])

def collision_detection(player_x, player_y):
    play_position = (player_x, player_y)
    if play_position in cannot_go_onto:
        print("collision detection")
        return False
    return True

编辑:

  • 由于不需要每次都重新创建数组,因此无法将\u放到函数外部。你知道吗
  • Made不能进入一个集合,这对搜索性能更好。(感谢托比亚斯·k指出)

相关问题 更多 >