import random import json from .player import Player from .map import Map from .entities import Town class Game: def __init__(self): self.players = [Player('P1'), Player('P2')] self.map = Map((20, 16)) self.towns = [] self.towers = [] self.mobs = [] def get_free_positions(self): positions = self.map.get_positions() positions = positions.difference([el.coords for el in self.towns]) positions = positions.difference([el.coords for el in self.towers]) return positions def get_random_position(self): return random.choice(tuple(self.get_free_positions())) def seed_map(self): self.towns.append(Town(self.players[0], self.get_random_position())) self.towns.append(Town(self.players[1], self.get_random_position())) self.towns.append(Town(self.players[0], self.get_random_position())) self.towns.append(Town(self.players[1], self.get_random_position())) def serialize(self): naive = json.loads(json.dumps(self, default=lambda o: o.__dict__)) def reduce_player(entities): for obj in entities: obj['player'] = obj['player']['id'] def make_id_based(entities): return {obj['id']: obj for obj in entities} for entity_type in ['towns', 'mobs', 'towers']: reduce_player(naive[entity_type]) naive[entity_type] = make_id_based(naive[entity_type]) naive['players'] = make_id_based(naive['players']) return naive