def build_object(object, world: esper.World, window_options, draw2entity): logger = logging.getLogger(__name__) mxCell = object[0] mxGeometry = mxCell[0] # Get X, Y coordinates x = float(mxGeometry.attrib.get('x', 0)) y = float(mxGeometry.attrib.get('y', 0)) width = float(mxGeometry.attrib.get('width', 0)) height = float(mxGeometry.attrib.get('height', 0)) pos = Position(x, y, 0, width, height) x += (width // 2) y += (height // 2) # Get the Map for simulation or create one # Entity 1 is the simulation entity if world.has_component(1, Map): simulation_map = world.component_for_entity(1, Map) else: simulation_map = Map() world.add_component(1, simulation_map) # Get POI tag if 'tag' in object.attrib: tag = object.attrib['tag'] else: tag = 'POI_' + str(len(simulation_map.pois)) logger.warning(f'POI ({x}, {y}) with no TAG. Using {tag}') simulation_map.pois[tag] = (x, y) # Alternatively display the POI if object.attrib.get('display', False): skeleton = Skeleton(object.attrib['id'], mxCell.attrib['style'], tag) world.create_entity(pos, skeleton) return {}, [], {}
def ParseFile(lines: Iterable[str], world: esper.World): working = world.create_entity() world.add_component(working, Passport(True)) for line in lines: words = line.strip().split() if not words: working = world.create_entity() world.add_component(working, Passport(True)) for word in words: tag, value = word.split(":") world.add_component(working, FIELD_TO_COMPONENT[tag](value))
class Main: def __init__(self): self.world = World() self.world.add_processor(DisplayProcessor(), priority=30) self.world.add_processor(InputProcessor(), priority=20) self.world.add_processor(GameStateProcessor(), priority=100) self.world.create_entity(GameState.TITLE_SCREEN) def core_game_loop(self): while True: self.world.process()
def asteroid(world: esper.World) -> int: global asteroid_counter asteroid_counter += 1 return world.create_entity( Renderable("#", colors.OBJECT_JUNK), Selectable(), Destructable(20, 100, 0), Velocity(0, 0), Name("Asteroid", f"AST-{asteroid_counter:05d}") )
def enemy_fighter(world: esper.World) -> int: return world.create_entity( Position(10, 10), Renderable("V", colors.OBJECT_ENEMY), Velocity(0, 0), Acceleration(0, 0, 0.001), Selectable(), Destructable(10, 20, 20), Damageable(), Behaviour(), Name("Some wanker", "WNK-80085") )
def player_ship(world: esper.World) -> int: return world.create_entity( Player(), Position(0, 0), Renderable("@", colors.OBJECT_PLAYER), Velocity(0, 0), Acceleration(0, 0, 0.001), Selectable(), Destructable(1000, 1000, 1000), Damageable(), Behaviour(), Name("Player ship", "PLR-12345") )
def build_object(cell, world: World, window_options, draw2entity): (components, style) = mxCellDecoder.parse_object(cell, window_options) ent = world.create_entity() # Custom components for key, val in cell.attrib.items(): if key.startswith('component_'): component_name = key[10:] # removes "component_" from the name init_values = json.loads(val) component = dynamic_importer.init_component( component_name, init_values) components.append(component) print(components) for c in components: world.add_component(ent, c) return {style['id']: [ent, style]}, [(ent, style['id'])], {}
def build_simulation_objects(content_root: Element, world: esper.World, window_options: WindowOptions, available_builders: dict): """ Parses the XML Elements into esper entities. Parsing is done by transforming Element's attributes and annotations into components. There are 2 types of objects: 1. Untyped objects -- Do not possess any type annotation. Used for building walls, for example. They have only basic components (e.g. Collision, Position, ...) 2. Typed objects -- Possess a type annotation. Enclosed in <object> tags in the XML file. Parsed by a specific builder according to the type. Not all typed objects are transformed into entities. RETURNS: draw2entity: dict -- Maps ids from drawio to entities in the simulation. objects: list -- List of typed objects that have been transformed into entities. interactive: dict -- Maps what entities can be interacted with (e.g. picked up). Key is the entity name, value is the entity id """ logger = logging.getLogger(__name__) logger.info(f'Available builders: {available_builders}') draw2entity = {} objects: List[Tuple[int, str]] = [] interactive = {} # If any object in the XML has dependencies that appear after it in the XML # The builder can return a DependencyNotFound error, causing the cell to be deferred. # Deferred cells are re-evaluated after the first pass is complete. deferred: List[Element] = [] # 1st pass for cell in content_root: if cell.tag == 'mxCell' and 'style' in cell.attrib: (components, style) = mxCellDecoder.parse_mxCell(cell, window_options) ent = world.create_entity() for c in components: world.add_component(ent, c) draw2entity[style['id']] = [ent, style] if cell.tag == 'object': cell_type = cell.attrib['type'] try: pending_updates = \ available_builders[cell_type].__dict__['build_object'](cell, world, window_options, draw2entity) draw2entity.update(pending_updates[0]) objects += pending_updates[1] interactive.update(pending_updates[2]) except DependencyNotFound as err: deferred.append(cell) logger.debug(f'Cell {cell.tag} deferred - {err}') # 2nd pass for cell in deferred: if cell.tag == 'mxCell' and 'style' in cell.attrib: (components, style) = mxCellDecoder.parse_mxCell(cell, window_options) ent = world.create_entity() for c in components: world.add_component(ent, c) draw2entity[style['id']] = [ent, style] if cell.tag == 'object': cell_type = cell.attrib['type'] try: pending_updates = \ available_builders[cell_type].__dict__['build_object'](cell, world, window_options, draw2entity) draw2entity.update(pending_updates[0]) objects += pending_updates[1] interactive.update(pending_updates[2]) except DependencyNotFound as err: logger.error(f'Cell {cell.tag} failed processing - {err}') return draw2entity, objects, interactive
def build_simulation_objects(content_root, batch: pyglet.graphics.Batch, world: esper.World, window_options): # Create Walls draw2entity = {} interactive = {} objects = [] windowSize = window_options[0] for cell in content_root: if cell.tag == 'mxCell' and 'style' in cell.attrib: (components, style) = mxCellDecoder.parse_mxCell(cell, batch, window_options) ent = world.create_entity() for c in components: world.add_component(ent, c) draw2entity[style['id']] = [ent, style] if cell.tag == 'object': if cell.attrib['type'] == 'robot': (components, style) = mxCellDecoder.parse_object(cell, batch, window_options) ent = world.create_entity() # Custom components for key, val in cell.attrib.items(): if key.startswith('component_'): component_name = key[ 10:] # removes "component_" from the name init_values = json.loads(val) component = dynamic_importer.init_component( component_name, init_values) components.append(component) for c in components: world.add_component(ent, c) draw2entity[style['id']] = [ent, style] objects.append((ent, style['id'])) elif cell.attrib['type'] == 'pickable': skeleton = copy.copy(cell) (components, style) = mxCellDecoder.parse_object(cell, batch, window_options) pick = Pickable(float(cell.attrib['weight']), cell.attrib['name'], skeleton) components.append(pick) ent = world.create_entity() for c in components: world.add_component(ent, c) interactive[style['name']] = ent elif cell.attrib['type'] == 'path': mxCell = cell[0] points = Path.from_mxCell(mxCell, windowSize[1]) obj = mxCell.attrib.get('source', None) (ent, _) = draw2entity.get(obj, (None, None)) if ent is None: print(f"Path origin ({obj}) not found. Trying target.") else: print(f"Adding path to entity {ent}") world.add_component(ent, Path(points)) elif cell.attrib['type'] == 'map-path': mxCell = cell[0] points = Path.from_mxCell(mxCell, windowSize[1]) objId = cell.attrib.get('origin', '') key = cell.attrib.get('key', '') if key == '': print(f"Map entry without key. Using default value") key = 'Default' (ent, _) = draw2entity.get(objId, (None, None)) if ent is None: print(f"Path origin ({obj}) not found. Trying target.") else: if world.has_component(ent, Map): map = world.component_for_entity(ent, Map) if key == 'Default': key += str(len(map)) map.paths[key] = points else: if key == 'Default': key += '0' newMap = Map({key: points}) world.add_component(ent, newMap) else: print("Unrecognized object", cell) return draw2entity, objects, interactive