Currently I'm developing a RTS game using Python/PyGame and I got some problems with fps drops when there are many units on the screen.
Using Snakeviz profiling I found out that the function update_vision()
takes up a big majority of the processing.
This is because the function is checking every tile inside a radius of each unit (depending on the units defined vision range). When there are many units there are a lot of calculations that need to happen.
I'd like to optimize this somehow. Currently it's checking the same tiles over and over if the units vision ranges are overlapping. However I'm not sure how to go about this and would appreciate any help!
Below is the function used for inputting 1s into the matrixes that represent the map. 1s represent vision in both cases. At the start of every frame the matrixes are reset with 0s.
#-----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:
for row in range(-unit.vision_range, unit.vision_range + 1):
for col in range(-unit.vision_range, unit.vision_range + 1):
loc_x = unit.x_coord + row
loc_y = unit.y_coord + 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