skifans
skifans

Reputation: 125

Searching array in python

I am trying to code the section of a game which will handle the collision detection. Currently it looks like this

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

This works fine for the coordinates (0,520),(20,500) & (40,460) however it doesn't work for the coordinate (20,480). I think this is because of the line

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

The index search is returning 1 because it simply takes the first time 20 appears in the array twice. Therefore only the position (20,500) is checked as it appears first in the array. However I don't know how to fix this problem. Any ideas/help would be hugely appreciated.

Upvotes: 0

Views: 63

Answers (1)

RvdK
RvdK

Reputation: 19790

Wouldn't it be simpler to just have an array of the no access coordinates, instead of 2 seperate lists.

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

Edit:

  • Placed cannot_go_onto outside the function because there is no need to recreate the array everytime.
  • Made cannot_go_onto a set, which is better for searching performances. (Thanks tobias_k for pointing it out)

Upvotes: 4

Related Questions