0

I am making an RTS game using PyGame.

Code below checks whether tiles are withing the range of a sprites defined vision range. If in range of vision range and inside the "diamond" shape then a "1" value is inserted into matrixes for representing the map (which are later used for drawing tiles).

The code is currently not optimized for the amount of sprites I would like to be able to render in my game. Especially with many sprites there are noticeable lag. Maybe there is a way to reduce overlapping vision by multiple sprites which are close to each other?

Thankful for any suggestions!

#-----Update vision & explored matrixes-----
def update_vision(self):

    for i, group in enumerate(all_p_unit_sprite_list):
        if i+1 != self.player:
            continue
        
        for unit in group:
            rel_x, rel_y = unit.get_coord()

            for row in range(-unit.vision_range, unit.vision_range + 1):
                for col in range(-unit.vision_range, unit.vision_range + 1):

                    loc_x = rel_x + row
                    loc_y = rel_y + col

                    if 0 <= loc_x < matrix_width and 0 <= loc_y < matrix_height:

                        if abs(row) + abs(col) <= unit.vision_range:

                            map_vision_matrix[loc_y][loc_x] = 1
                            map_explored_matrix[loc_y][loc_x] = 1
#-----Get grid coordinates-----
def get_coord(self):
    col = self.rect.centerx  // tile_size
    row = self.rect.centery // tile_size
    return (col, row)
Zoler1337
  • 108
  • 5
  • Are you able to create a [mcve] that demonstrates the issue? Have you tried [profiling](https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script) your code to identify bottlenecks? – import random Apr 07 '22 at 01:59
  • Thank you for your comment. I have done a profiling using the Snakeviz module. It showed that around 60% of the processing was coming from the functions I attached. Which is a very short code compared to the massive functions used to calculate the sprites movement etc. – Zoler1337 Apr 07 '22 at 15:58
  • Do you really need a seperate function to get the coordinates? Can't you calculate the coordinates in the loop itself? That would save out a function call. – The_spider Apr 08 '22 at 19:19

0 Answers0