How do I get the position in a 2D Numpy array when iterating?

Viewed 1154

I have a 2D Numpy array representing a level map in a tile-based game I'm making in Python3.7. My array is 50 rows x 50 columns, and each value is an integer number representing a sprite type (various wall parts, floors, etc). When I iterate through the array and find a wall sprite (for example), I want to know the row and column number of that value so I can reference it directly.

It seems such a simple thing, but I can't seem to find the right Numpy function that will iterate through the 2D array and return the position[row, col]of each one it finds. I can then calculate it's relative position on the screen using the array position, and then test collision with .colliderect().

EDIT: For more clarity, I'm adding the fact that I need to compare each integer value in the array to aList of wall parts (also integers), and if it's in the list, return the array position.

TL;DR How do I iterate through a Numpy 2darray and return the[row, col] for each match instead of the value?

2 Answers

Just use np.argwhere.

Example:

>>> import numpy as np
>>> a = np.zeros((50, 50))
>>> a[3, 4] = 1
>>> a[4, 5] = 1
>>> for i, j in np.argwhere(a == 1): print(i, j)
... 
(3, 4)
(4, 5)

(The above example was run using python 2, hence the tuples in the output shown, but it is otherwise exactly the same in python 3.)

I'm thinking that you could use nested for-loops and a data structure like below:

let's say map is a 2-D numpy array and that 1 represents a wall type and 2 represents a floor type.

code:

locationsToSprites = dict()#Data structure that stores the locations of the sprite type. 
for row in range(0, len(map)): #looping through all rows
    for col in range(0, len(map[row])):#looping through all columns of a row
        if(map[row][col] == 1):
            locationsToSprites[(row, col)] = 'the wall type'
        elif(map[row][col] == 2):
            locationsToSprites[(row, col)] = 'the floor type'

Now, because a dictionary was used to store the locations of the sprites we can just print the keys of the dictionary to get all the locations.

Related