Search code examples
pythonpygame

How can I make a loop to perform action on Neighbours of my start box in python?


I have made a grid using for loop and pygame :

image

and I have also connected it to a 2d-array. I have converted x, y into rows and columns according to the blocks.

now the green block represents the start position and I have to perform actions on its neighbors i.e all blocks touching it(even the corner blocks)

I wanted to know is there a more efficient solution to this as currently I am just storing them one-by-one in a list and then perform actions on it.

Like a loop or something like that.

and to get the row and column of each it takes a lot of code so please help I am a beginner.

Till now I have done something like this(I know this is the worst way)

self.neighboursx.append(self.start_point_column)
self.neighboursy.append(self.start_point_row - 1)

self.neighboursx.append(self.start_point_column + 1)
self.neighboursy.append(self.start_point_row - 1)

self.neighboursx.append(self.start_point_column + 1)
self.neighboursy.append(self.start_point_row)

self.neighboursx.append(self.start_point_column - 1)
self.neighboursy.append(self.start_point_row + 1)

self.neighboursx.append(self.start_point_column)
self.neighboursy.append(self.start_point_row + 1)

self.neighboursx.append(self.start_point_column - 1)
self.neighboursy.append(self.start_point_row + 1)

Solution

  • To loop through a 2D array, you could do something like:

    for col in range(number_of_columns:
        for row in range(number_of_rows):
            do_something(col, row)
    

    For your neighbour checking function:

    def do_something(col, row):  # e.g. count neighbours of a boolean 2D array dd
        count = 0
        for x in range(-1, 2): # -1, 0, 1
            for y in range(-1, 2):
                try:
                    if dd[col +x][row + y]: 
                        count += 1
                except IndexError:  # cell is outside array
                    pass
            # but we don't want to count ourselves,
            if dd[col][row]:
                count -= 1
        # now do something with the count
        …