def test_23_power(self): tl = Entity('POWER-0', EntityType.find(100), 'Power plug') tl.assigned_id = 1 tl.last_checkin = time.time() - 3600 # one hour before tl.save() self.printall() print tl
def __init__(self, scene, pos, dest, router): Entity.__init__(self) self._destroyed = False self._closing = False self._target_reached = False self._scene = scene self._map = scene.getMap() self._path = None self._dying_t = 0 self._spin = 0 self.moveTo(pos) self._scale = 1.0 self._graphics = R.loadObject("enemy.obj","diffuse") self._orient_m= T.identity_matrix() self._xform_m = N.dot(T.rotation_matrix(math.pi/2,(0,0,1)),T.scale_matrix(self._scale)) bounds = self._graphics.getObj().getBounds() router.requestJob(pos, dest, Enemy.OnRouteObtained, self) Entity.setBounds(self,bounds * self._scale) self._destroyed = False self._old_time = 0 self._old_pos = None # At t-1 self._old_pos2 = None # At t-2 self._hc = HeadingController()
def __init__(self, pos=Vector(0, 0), rot=0.0): """Creates a new Ship Args: pos: the position of the ship rot: the rotation of the ship Returns: a new Ship instance """ # Get the initial direction of the ship using the rotation direction = Vector(cos(radians(rot)), sin(radians(rot))) # Initially, the ship isn't moving self._movement = Vector.zero() # Initialize bullet list self.bullets = [] self._last_shoot = self._shoot_delay self._last_teleport = self._teleport_delay self.teleport_up = True self.effect_player = EffectPlayer.instance() Entity.__init__(self, (20, 0, -30, 20, -30, -20), direction, lin_speed=1.0, rot_speed=2.0, pos=pos, rot=rot, scale=0.5)
def __init__(self, hours=0, minutes=0, seconds=0): Entity.__init__(self, 0) # For this demo, the clock need not have mass. Intervaled.__init__(self, Clock.INTERVAL, Milli()) self.hours = hours self.minutes = minutes self.seconds = seconds
def __init__(self, x, y, name, color="#000000", image_file=None, flip=False, force_background=False, jump_sound=None): Entity.__init__(self) self.name = name self.color = color self.xvel = 0 self.yvel = 0 self.onGround = False self.onStairs = False self.onBar = False self.on_goal = False self.image = draw_player(self.color, image_file, flip, force_background) self.rect = Rect(x, y, constants.TILE_X - 2, constants.TILE_Y) if jump_sound is None: self.jump_sound = None else: self.jump_sound = pygame.mixer.Sound(jump_sound) self.jump_sound.set_volume(1.0)
def __init__(self, scene, pos): Entity.__init__(self) self._destroyed = False self._closing = False self._scene = scene self.moveTo(pos) self._graphics = R.loadObject("targetpt.obj","diffuse") self._beacon = R.loadObject("beacon.obj","glow") self._anim_m = T.identity_matrix() self._rot= T.quaternion_about_axis(0, (0,0,1)) self._rot_speed = T.quaternion_about_axis(0.01, (0,0,1)) self._scale = 0.15 self.moveTo(self.getPosition() + (0,0,-0.3)) self._scale_m = T.scale_matrix(self._scale) bounds = self._graphics.getObj().getBounds() * self._scale Entity.setBounds(self,bounds)
def update(self, time): if self._destroyed: return False if self._t0 is None: self._t0 = time if self._follow is not None and not self._follow.closing() : d = self._follow._pos - self._pos T.unit_vector(d,d) self._dir = self._dir * (1-self._thrust) + d * self._thrust if time - self._t0 > 3000 or self._follow._destroyed: print "Not following anymore" self._follow = None Entity.moveTo(self, self._pos + self._dir * self._speed) # also updates _pos else: # too simple to use Verlet Entity.moveTo(self, self._pos + self._dir * self._speed) # also updates _pos self._dir += self._gravity self._xform = mmult(self._pos_m,self._scaling_m, T.quaternion_matrix(self._rotation)) self._rotation = T.quaternion_multiply(self._d_rotation, self._rotation) # hit the floor if self._map(self._pos[0], self._pos[1], False) > self._pos[2]: self.explode() return False # tell the scene the missile is toast return True
def __init__(self, map, position): print "New player" Entity.__init__(self) self._lock = None self._phys = Verlet(position) self._phys.setDamping((0.02, 0.02, 0.0002)) self._phys.setGravity((0, 0, -0.00006)) self._on_floor = False self._speed = 0 self._map = map self._heading = 0 self.reset() r = self._radius = 0.1 self.setBounds(((-r, -r, -r), (r, r, r))) # entity stuff Entity.moveTo(self, position) # keep the entity updated self._scaling = T.scale_matrix(self._radius) self._last_pos = N.array((0, 0, 0), dtype="f") self._graphics = R.loadObject("sphere.obj", "diffuse")
def test_merge_rels(self): entity1 = Entity(serves=['a','b','c']) entity2 = Entity(serves=['c','d','e']) entity1.merge(entity2) serves = ['a', 'b', 'c', 'd', 'e'] assert len(entity1.data['serves']) == 5 for i in serves: assert i in entity1.data['serves']
def __init__(self, poi_type, red, black): Entity.__init__(self, poi_type, red, black) self.width = 90 self.height = 90 self.offsetRed = self.height / 2 self.offsetBlack = self.width / 2 self.conceal()
def __init__(self, poi_type, red, black): Entity.__init__(self, poi_type, red, black) self.width = 90 self.height = 90 self.offsetRed = self.height/2 self.offsetBlack = self.width/2 self.conceal()
def test_pclink(self): entity1 = Entity() entity2 = Entity() assert len(entity1.children) == 0 assert len(entity2.parents) == 0 entity1.pclink(entity1, entity2) assert len(entity1.children) == 1 assert len(entity2.parents) == 1
def test_merge_existing_pass(self): entity1 = Entity() entity1.add_identifier('abc') entity2 = Entity() entity2.add_identifier('abc') entity1.merge(entity2) assert len(entity1.identifiers()) == 1 assert entity1.identifiers()[0] == 'abc'
def __init__(self, door_type, red, black, red_link, black_link): Entity.__init__(self, door_type, red, black) self.red_link = red_link self.black_link = black_link self.key = "door-{}-{}-{}-{}".format(red, black, red_link, black_link) self.width = 100 self.height = 100 self.set_offset() self.close()
def create_match(self): self.width = random.randint(25, 50) self.height = random.randint(25, 50) self.tiles = {} for y in range(self.height): for x in range(self.width): self.tiles[(x, y)] = 'grass' test_entity = Entity('test_ape', self, (0, 0), Item('bomb', self)) test_entity.use()
def __init__(self, mass, position, velocity): Entity.__init__(self, mass) Positioned.__init__(self, position) Moving.__init__(self, velocity) self.radius = mass / 2 self.color = (127, 127, 0) self.accumulatedTime = 0 self.environment = None self.halt = False
def test_merge(self): data = ['abc', 'def'] entity1 = Entity() entity1.add_identifier('abc') entity2 = Entity() entity2.add_identifier('def') entity1.merge(entity2) assert len(entity1.identifiers()) == 2 for i in entity1.identifiers(): assert i in data
def __init__( self, level_loaded: Level, x, y, name, key_up, key_down, key_right, key_left, bg_color="#000000", image_file=None, image_transform=None, flip=False, force_background=False, jump_sound=None, ): Entity.__init__(self) self.collides = True self.has_grip = False self.item = False self.collectable = False self.transformed = False self.fly = False self.target_player = None self.path = None self.path_last_calc = pygame.time.get_ticks() self.name = name self.level_loaded = level_loaded self.key_up = key_up self.key_down = key_down self.key_right = key_right self.key_left = key_left self.key_pressed_up = False self.key_pressed_down = False self.key_pressed_left = False self.key_pressed_right = False self.bg_color = bg_color self.vel_x = 0 self.vel_y = 0 self.onGround = False self.onStairs = False self.onBar = False self.on_goal = False self.image = draw_player(level_loaded, self.bg_color, image_file, flip, force_background) self.image_transform = image_transform self.rect = Rect(x, y, level_loaded.TILE_X-2, level_loaded.TILE_Y) if jump_sound is None: self.jump_sound = None else: self.jump_sound = pygame.mixer.Sound(jump_sound) self.jump_sound.set_volume(1.0)
def control(self, controller, command, value=None): if command.id == COMMAND_ON.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x01) ]) self.log_command('Turning the power on') return elif command.id == COMMAND_OFF.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x00) ]) self.log_command('Turning the power off') return Entity.control(self, command, value=value)
def __init__(self, timer, frameRate=FRAME_RATE, mass=0): Entity.__init__(self, mass) resolution = Milli() Intervaled.__init__(self, 1 / (resolution.scalor * frameRate), resolution) self.viewer = None self.overlay = None self.sensor = None self.mount = None self.lens = None # The camera should always start living. self.birth() # TODO: Or maybe wait when it's added to the environment?
def mockEntity(self, locale): """Mock an entity Args: locale (string): a locale string e.g: en, fr, ... Returns: A dict representing an entity """ entity = Entity(content=None) entity.locale = locale return entity
def __init__(self, name, password=None): Entity.__init__(self) self.create_ts = datetime.now() self.name = name self.seed = sum([ord(i) for i in self.id]) self.password = password self.history = [] self.current = None self.locked = False self.players_auth_ids = [] self.stunned = False self.result = None
def test_merge_tags(self): entity1 = Entity() entity1.set_tag('foo','bar') entity2 = Entity() entity2.set_tag('cat','dog') entity1.merge(entity2) tags = entity1.tags() assert tags['foo'] == 'bar' assert tags['cat'] == 'dog'
def __init__(self, position, velocity, rayColor=None): Entity.__init__(self, 0) # Light rays have 0 mass. For now. Positioned.__init__(self, position) Moving.__init__(self, velocity) self.velocityModifier = None self.rayColor = rayColor if rayColor else (int(random() * 255), int(random() * 255), int(random() * 255)) self.segment = None self.bounces = RAY_BOUNCES self.timeResolution = Milli() self.accumulatedTime = 0 self.environment = None
def __init__(self, pos, particles): Entity.__init__(self) self._particles = particles self.moveTo(pos) self._graphics = R.loadObject("base.obj","diffuse") self._anim_m = T.identity_matrix() bounds = self._graphics.getObj().getBounds() Entity.setBounds(self,bounds)
def state_changed(self, state_message): Entity.state_changed(self, state_message) state = state_message[0] if state == 0x00: if 0 != self.state_value: self.set_state(STATE_OFF, 0) return True elif state == 0x01: if 1 != self.state_value: self.set_state(STATE_ON, 1) return True return False
def body(self): # Case 1: nothing body = self.soup_message.get_body() if not body: return {} # Case 2: urlencoded content_type, type_parameters = self.get_header('content-type') if content_type == 'application/x-www-form-urlencoded': return decode_query(body) # Case 3: multipart if content_type.startswith('multipart/'): boundary = type_parameters.get('boundary') boundary = '--%s' % boundary form = {} for part in body.split(boundary)[1:-1]: # Parse the entity entity = Entity(string=part) # Find out the parameter name header = entity.get_header('Content-Disposition') value, header_parameters = header name = header_parameters['name'] # Load the value body = entity.get_body() if 'filename' in header_parameters: filename = header_parameters['filename'] if filename: # Strip the path (for IE). filename = filename.split('\\')[-1] # Default content-type, see # http://tools.ietf.org/html/rfc2045#section-5.2 if entity.has_header('content-type'): mimetype = entity.get_header('content-type')[0] else: mimetype = 'text/plain' form[name] = filename, mimetype, body else: if name not in form: form[name] = body else: if isinstance(form[name], list): form[name].append(body) else: form[name] = [form[name], body] return form # Case 4: This is useful for REST services # XXX Should just return the body as a string? deserialized? return {'body': body}
def place_landmark(self): player_room = self.get_rooms()[0] farest_room = None farest_distance = 0 for room in self.get_rooms(): if room != player_room: distance = self.distance_room_to_room(player_room, room) if distance >= farest_distance: farest_distance = distance farest_room = room else: continue center_room_x, center_room_y = farest_room.center landmark_component = Landmark(self.dungeon.current_floor + 1) landmark = Entity( self.dungeon.game, center_room_x, center_room_y, ">", libtcod.yellow, "Landmark", render_order=RenderOrder.LANDMARK, landmark=landmark_component, ) self.add_entity(landmark)
def test_12_modify2(self): te = Entity.find( 'UID-1234' ) te.state = STATE_OFF te.state_value = None te.last_checkin = time.time() te.save() self.printall()
def test_geom_notimplemented(self): # requires geohash() and point() to be implemented. entity = Entity(**self.expect) with self.assertRaises(NotImplementedError): entity.geohash() with self.assertRaises(NotImplementedError): entity.point() with self.assertRaises(NotImplementedError): entity.bbox()
def state_changed(self, state_message): Entity.state_changed(self, state_message) state = state_message[0] if 0x00 < state < 0xFF: state = int(round((state * 100.0) / 255.0)) if self.state_value != state: self.set_state(STATE_ON, state) return True elif state == 0x00 and 0 != self.state_value: self.set_state(STATE_OFF, 0) return True elif state == 0xFF and 100 != self.state_value: self.set_state(STATE_ON, 100) return True return False
def __init__( self, level_loaded: Level, x, y, name, bg_color="#000000", image_file=None, image_transform=None, flip=False, force_background=False, jump_sound=None ): Entity.__init__(self) self.collides = False self.has_grip = False self.item = False self.collectable = False self.transformed = False self.fly = False self.level_loaded = level_loaded self.name = name self.bg_color = bg_color self.xvel = 0 self.yvel = 0 self.onGround = False self.onStairs = False self.onBar = False self.on_goal = False self.image_file = image_file self.image_right = draw_player( level_loaded.TILE_X, level_loaded.TILE_Y, self.bg_color, image_file, True ) self.image_left = draw_player( level_loaded.TILE_X, level_loaded.TILE_Y, self.bg_color, image_file, False ) self.image = self.image_right self.image_transform = image_transform self.rect = Rect(x, y, level_loaded.TILE_X-2, level_loaded.TILE_Y) if jump_sound is None: self.jump_sound = None else: self.jump_sound = pygame.mixer.Sound(jump_sound) self.jump_sound.set_volume(1.0)
def create(self): """ Creates a new entity and unique id and returns it """ entity = Entity.entity(self.nextEntityID) self.entities[self.nextEntityID] = entity self.nextEntityID = self.nextEntityID + 1 return entity["entityID"]
def test_24_power_state_plus_control(self): tl = Entity.find( 'POWER-0' ) tl.control(COMMAND_ON) self.printall() print tl tl.set_state(STATE_ON) self.printall() print tl
def control(self, controller, command, value=None): if command.id == COMMAND_LIGHT_LEVEL.id: if value is not None: msg = [ chr(0x00), chr(0x02), chr(int(round((int(value) * 255) / 100))) ] controller.send_message(self.unique_id, msg) self.log_command('Setting light level to ' + str(value)) return elif command.id == COMMAND_ON.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x01) ]) self.log_command('Turning the light on') return elif command.id == COMMAND_OFF.id: controller.send_message(self.unique_id, [ chr(0x00), chr(0x00) ]) self.log_command('Turning the light off') return Entity.control(self, command, value=value)
def test_11_modify1(self): te = Entity.find( 'UID-1234' ) te.name = 'Test entity 1' te.state = STATE_ON te.state_value = '30%' te.assigned_id = 0x01 te.last_checkin = time.time() te.save() self.printall()
def update(self, time): self._lock = None # ----- here be dragons ph = self._phys ph._impuse = ph._gravity ph.update() # test for collision with map z, normal = self._map(ph._position[0], ph._position[1]) h = (z + self._radius) - ph._position[2] T.unit_vector(normal, out=normal) self._on_floor = h > 0 if self._on_floor and ph._position[2] < ph._last_position[2]: # collision ph._impulse += h * normal * 0.00001 # * normal[2] ph._position[2] += h ph._last_position[2] += h new_pos = ph._position # ----- self._dir = new_pos - self._pos self._speed = T.vector_norm(self._dir) self._last_pos[:] = new_pos Entity.moveTo(self, new_pos) # updates self._pos too self._normal = normal self._axis = N.cross(self._dir, normal) self.roll(self._axis)
def populate_tiles(self): mapContainer = [ x.strip() for x in open('src/map/MAPS.txt', encoding='utf-8-sig') ] for i in range(int(self.gameMap.mapHeight / self.gameMap.entityHeight)): for j in range( int(self.gameMap.mapWidth / self.gameMap.entityWidth)): temp = Entity() temp.positionWidth = self.gameMap.mapOffSetWidth + ( j * self.gameMap.entityWidth) temp.positionHeight = self.gameMap.mapOffSetHeight + ( i * self.gameMap.entityHeight) if mapContainer[i][j] == '1': self.entityContainer.append(temp) else: temp.canBePassed = False self.entityContainer.append(temp)
def receive(self, address, unique_id, flags, data): ''' Processes received data from a physical device. ''' DeviceHandler.receive(self, address, unique_id, flags, data) entity = Entity.find(unique_id) if entity is None: print 'No device found with id:', unique_id else: if entity.state_changed(data): ClientModule.instance().send_state_change(entity)
def send_message(self, unique_id, message): ''' Sends a message to the entity identified by "unique_id". ''' entity = Entity.find(unique_id) if entity is None: print 'No device found with id:', unique_id else: if entity.entity_type.comm_type == EntityType.COMM_TYPE_RADIO: self.__radio_handler.send(unique_id, message) else: print 'No communication type found for:', entity.entity_type, '| entity:', entity
def __init__(self, texture = None, position = Point2(0, 0), depth = 55, scale = 1, transparency = True): Entity.__init__(self, "shapes/plane") self.prime.reparentTo(base.camera) self.prime.setPos(Point3(position.getX(), depth, position.getY())) self.prime.setScale(scale) # tells panda3d to not care about what order to draw the sprite in, prevents # z-fighting self.prime.setBin("unsorted", 0) # tells panda3d not to check if something has been drawn in front of it self.prime.setDepthTest(False) if transparency: self.prime.setTransparency(1) if texture: self.texture = base.loader.loadTexture(APP_PATH + "media/textures/" + texture + ".png") self.prime.setTexture(self.texture, 1)
def autoload_fields_by_row(entity, row, prefix=''): """ Autoloads entity fields from imported data row. entity: core.importhandler.Entity entity, where we need add fields and subentities. row: dict data, loaded from datasource. prefix: string prefix to be added to the name. """ def getjson(x): try: res = json.loads(x) except: return None return res from entities import Entity, Field for key, val in row.iteritems(): data_type = 'string' if key not in entity.fields: if isint(val): data_type = 'integer' elif isfloat(val): data_type = 'float' else: item_dict = getjson(val) if item_dict: entity.fields[key] = Field( { 'name': key, 'column': key, 'transform': 'json' }, entity) if key not in entity.nested_entities_field_ds: json_entity = Entity(dict(name=key, datasource=key)) autoload_fields_by_row(json_entity, item_dict, prefix='{0}.'.format(key)) entity.nested_entities_field_ds[key] = json_entity continue if prefix: field_config = { 'name': prefix + key, 'jsonpath': '$.{0}'.format('.'.join(key.split('-'))) } else: field_config = {'name': key, 'type': data_type, 'column': key} entity.fields[key] = Field(field_config, entity) entity.fields_loaded = True
def test_onestop_notimplemented(self): # requires geohash() to be implemented. entity = Entity(**self.expect) with self.assertRaises(NotImplementedError): entity.id() with self.assertRaises(NotImplementedError): entity.onestop()
def get_multipart_body(self, body): content_type, type_parameters = self.get_header('content-type') boundary = type_parameters.get('boundary') boundary = '--%s' % boundary form = {} for part in body.split(boundary)[1:-1]: # Parse the entity entity = Entity(string=part) # Find out the parameter name header = entity.get_header('Content-Disposition') value, header_parameters = header name = header_parameters['name'] # Load the value body = entity.get_body() if 'filename' in header_parameters: filename = header_parameters['filename'] if filename: # Strip the path (for IE). filename = filename.split('\\')[-1] # Default content-type, see # http://tools.ietf.org/html/rfc2045#section-5.2 if entity.has_header('content-type'): mimetype = entity.get_header('content-type')[0] else: mimetype = 'text/plain' form[name] = filename, mimetype, body else: if name not in form: form[name] = body else: if isinstance(form[name], list): form[name].append(body) else: form[name] = [form[name], body] return form
def create_bomb(coord=None): return Entity(components=OrderedDict([ (Component.LOCATION, components.location.StaticLocationComponent(coord=coord)), (Component.EXPLOSION, components.ExplosionComponent(power=2.0, time=3.0)), (Component.DRAW, components.draw.DrawCircleComponent(size=0.8, color=(255, 0, 0), color_by_state=OrderedDict([ ('flashing', (255, 128, 128)), ]))), ]))
def test_add_identifier(self): data = ['abc', 'def'] entity = Entity() for k in data: entity.add_identifier(k) assert len(entity.identifiers()) == 2 for i in entity.identifiers(): assert i in data
def old_create_entity_item(game, item_defname, x, y, dict_attributes): name = dict_attributes.get("name", "?") appearance = dict_attributes.get("char", "?") color = dict_attributes.get("color", libtcod.red) use_function = dict_attributes.get("use_function", None) power = dict_attributes.get("power", 0) equippable = dict_attributes.get("equippable", False) target = dict_attributes.get("target", None) value = dict_attributes.get("value", 30) if equippable: equippable_slot = equippable.get("slot", EquipmentSlot.NONE) equippable_weapon_dmg = equippable.get("weapon_damage", (0, 2)) equippable_dmg_bonus = equippable.get("physical_power_bonus", 0) equippable_might_bonus = equippable.get("might_bonus", 0) equippable_hp_bonus = equippable.get("hp_bonus", 0) equippable_vitality_bonus = equippable.get("vitality_bonus", 0) equippable_dexterity_bonus = equippable.get('dexterity_bonus', 0) equippable_armor_bonus = equippable.get('armor_bonus', 0) equippable_component = Equippable( equippable_slot, weapon_damage=equippable_weapon_dmg, physical_power_bonus=equippable_dmg_bonus, might_bonus=equippable_might_bonus, hp_bonus=equippable_hp_bonus, vitality_bonus=equippable_vitality_bonus, dexterity_bonus=equippable_dexterity_bonus, armor_bonus=equippable_armor_bonus) else: equippable_component = None item_component = Item(use_function=use_function, power=power, target_type=target, value=value) item = Entity( game, x, y, appearance, color, name, item=item_component, equippable=equippable_component, render_order=RenderOrder.ITEM, ) print("created item is {}, and equipable is {} ".format( item.name, item.equippable)) return item
def update(self, gameinfo): if gameinfo.my_fleets: src = gameinfo.my_fleets.values() dest = gameinfo.not_my_planets.values() for f in src: for p in dest: if Entity.distance_to(f,p) < f.vision_range() and int(f.num_ships) > int(p.num_ships) and int(f.dest.num_ships) > int(p.num_ships): gameinfo.fleet_order(f,p,f.num_ships) break return if gameinfo.my_planets and gameinfo.not_my_planets: dest = min(gameinfo.my_planets.values(), key = lambda p: p.num_ships) src = max(gameinfo.my_planets.values(), key = lambda p: p.num_ships) if src.num_ships > 50 and Entity.distance_to(src,dest) > 0 and dest.num_ships < 35: gameinfo.planet_order(src, dest, int(src.num_ships *0.30)) else: dest = max(gameinfo.not_my_planets.values(), key = lambda p: p.growth_rate) src = max(gameinfo.my_planets.values(), key = lambda p: p.num_ships) if len(self.orders_list) > 0: count = 0 for i in self.orders_list: if dest.id is self.orders_list[len(self.orders_list)-1].id and dest.id is not src.id: count +=1 if count is 2: if len(gameinfo.neutral_planets) > 0: dest = max(gameinfo.neutral_planets.values(), key = lambda p: p.growth_rate) else: dest = min(gameinfo.not_my_planets.values(), key = lambda p: p.num_ships) self.orders_list.clear() break if i is 2: break if src.num_ships > 30: gameinfo.planet_order(src, dest, int(src.num_ships *0.75)) self.orders_list.append(dest)
def create_entity(game, base_stats, entity_stats): if not entity_stats: entity_stats = base_stats name = entity_stats.get('name', base_stats.get('name', game_config.DEFAULT_NAME)) appearance = entity_stats.get( 'char', base_stats.get('char', game_config.DEFAULT_APPEARANCE)) color = entity_stats.get( 'color', base_stats.get('color', game_config.DEFAULT_COLOR)) entity = Entity(game, 0, 0, appearance, color, name) return entity
def create_coin(coord=None): return Entity(components=OrderedDict([ (Component.LOCATION, components.location.StaticLocationComponent(coord=coord)), (Component.HEALTH, components.HealthComponent()), (Component.COLLECTABLE, components.CollectableComponent()), ( Component.DRAW, components.draw.DrawCircleComponent( size=random.choice((0.4, 0.5, 0.6)), color=random.choice(( (255, 128, 32), # Copper (255, 255, 255), # Silver (255, 255, 0), # Gold )))), ]))
def create_player(coord=None): return Entity(components=OrderedDict([ (Component.BEHAVIOR, components.behavior.HumanPlayerInputComponent()), (Component.LOCATION, components.location.MovingLocationComponent(coord=coord, speed=10.0)), ('mining', components.MiningComponent()), (Component.COLLECTOR, components.CollectorComponent()), (Component.DRAW, components.draw.DrawRectangleComponent(size=0.8, color=(0, 196, 0), color_by_state=OrderedDict([ ('colliding', (255, 255, 0)), ('moving', (128, 255, 128)), ]))), ]))
def create_monster(coord=None): return Entity(components=OrderedDict([ (Component.BEHAVIOR, components.behavior.AgressiveAIComponent(walk_distance=15, attack_distance=10, walk_speed=3, attack_speed=5)), (Component.LOCATION, components.location.MovingLocationComponent(coord=coord, speed=3)), (Component.HEALTH, components.HealthComponent()), (Component.DRAW, components.draw.DrawRectangleComponent(size=0.8, color=(0, 128, 255), color_by_state=OrderedDict([ ('chasing', (255, 0, 255)), ]))), ]))
def entities_from_h5(fpath): from entities import Entity h5in = tables.open_file(fpath) h5root = h5in.root entities = {} for table in h5root.entities: entity = Entity.from_table(table) entities[entity.name] = entity globals_def = {} if hasattr(h5root, 'globals'): for table in h5root.globals: if isinstance(table, tables.Array): global_def = {'type': normalize_type(table.dtype.type)} else: global_def = {'fields': get_fields(table)} globals_def[table.name] = global_def h5in.close() return globals_def, entities