WMICraft/logic/spawner.py

37 lines
1.7 KiB
Python

import random
from common.constants import GRID_CELL_PADDING, GRID_CELL_WIDTH, GRID_CELL_HEIGHT
class Spawner:
def __init__(self, grid, objs_to_spawn_list: list, spawn_area_width=0, spawn_area_height=0, spawn_area_pos_row=0,
spawn_area_pos_column=0, spawn_where_possible=False): # kolumny i wiersze liczymy od 0;
self.objs_to_spawn_list = objs_to_spawn_list
self.spawn_area_width = spawn_area_width
self.spawn_area_height = spawn_area_height
self.spawn_area_pos_row = spawn_area_pos_row
self.spawn_area_pos_column = spawn_area_pos_column
self.grid = grid
self.spawn_where_possible = spawn_where_possible
def spawn(self):
if self.spawn_where_possible:
possible_fields = self.grid.free_fields
else:
possible_fields = []
for field in self.grid.free_fields:
if (self.spawn_area_pos_column <= field.column < (self.spawn_area_width + self.spawn_area_pos_column)) \
and (self.spawn_area_pos_row <= field.row < (self.spawn_area_height + self.spawn_area_pos_row)):
possible_fields.append(field)
for obj in self.objs_to_spawn_list:
ran_index = random.randint(0, len(possible_fields)-1)
ran_field = possible_fields[ran_index]
ran_field.busy = True
obj.rect = obj.rect.clamp(ran_field)
self.grid.busy_fields.append(ran_field)
if ran_field in self.grid.free_fields:
self.grid.free_fields.remove(ran_field)
if ran_field in possible_fields:
possible_fields.remove(ran_field)
obj.update()