def terrain_entity(x_step, width, pn_step, pn_step_offset, pn_mag): num_pts = int(width / x_step) + 6 pts = generate_points(pn_step, pn_mag, pn_step_offset, num_pts, x_step, 0) points_list = split_into_parts(pts) terrain_ent = entities.Entity(0, 0, points_list[0]) terrain_ent.render_component = components.PolygonRenderComponent( terrain_ent) terrain_ent.components[ components.CollisionComponent] = components.CollisionComponent( terrain_ent) shift_center(terrain_ent) close_shape(terrain_ent.points, 50) # die erstellten shapes in entitäten übertragen for i in range(1, len(points_list)): pts = points_list[i] ent = entities.Entity(0, 0, pts) ent.render_component = components.PolygonRenderComponent(ent) ent.components[ components.CollisionComponent] = components.CollisionComponent(ent) ent.set_parent(terrain_ent) shift_center(ent) ent.pos[0] -= x_step close_shape(ent.points, 50) return terrain_ent
async def assign_castle(player_name): x, y = generate_castle_position() castle = entities.Entity(x, y, 'castle', player_name) castles[player_name] = castle board_add_entity(castle) await broadcast_message('entity_created', [castle.uid, x, y, 'castle', 100, 1, player_name])
def get_byid(self,objid): """Instantiate the correct proxy object by ID.""" objinfo = entities.Entity(objid=str(objid)) objinfo.sesh = sesh entity = getattr(entities,objinfo['entitytype'])() entity.sesh = sesh entity.objid = objid return entity
def create_flavor_service(self): localized_name = entities.Entity(self).localized_name() self.addCleanupDelete('service') return self.default_admin_client.service.create_vm( 'flavor_service', localized_name=localized_name, vcpus=self.default_vcpus, ram=self.default_ram, disk=self.default_disk, network=self.default_network)
def CreateEntityFromRecipe(self, scene, recipe, entityItemID): newEntity = entities.Entity(scene, entityItemID) for componentID, initValues in recipe.iteritems(): componentName = entityCommon.GetComponentName(componentID) component = self.CreateComponent(componentName, initValues) if component is not None: newEntity.AddComponent(componentName, component) else: newEntity.AddComponentState(componentName, initValues) return newEntity
def ReceiveRemoteEntity(self, fromSceneID, entityID, sceneID, packedState): GameWorld.GetNetworkEntityQueueManager().AddEntity(entityID) scene = self.GetEntityScene(sceneID) entity = entities.Entity(scene, entityID) for componentName, state in packedState.iteritems(): componentFactory = self.componentFactories.get(componentName, None) if componentFactory: component = componentFactory.CreateComponent( componentName, state) component = componentFactory.UnPackFromSceneTransfer( component, entity, state) entity.AddComponent(componentName, component) else: entity.AddComponentState(componentName, state) return scene.CreateAndRegisterEntity(entity)
async def update_player(player): player.spawn_timer -= 1 if player.target is not None and player.spawn_timer <= 0: player.spawn_timer = entities.SPAWN_INTERVAL castle = castles[player.name] enemy_castle = castles[player.target] # TODO: find optimal side to spawn on given target spawn_x = castle.x spawn_y = castle.y + 2 minion = entities.Entity(spawn_x, spawn_y, "minion", player.name) board_add_entity(minion) path = pathfinding.find_path((spawn_x, spawn_y), (enemy_castle.x, enemy_castle.y), is_obstructed) minions[minion.uid] = path[1:] await broadcast_message('entity_created', minion.to_list())
def CreateEntityFromServer(self, entityID, sceneID, initialComponentStates): self.LogInfo('EntityClient creating server entity: ', entityID, 'with initial state:') self.LogInfo(initialComponentStates) GameWorld.GetNetworkEntityQueueManager().AddEntity(entityID) scene = self.LoadEntitySceneAndBlock(sceneID) scene.WaitOnStartupEntities() entity = entities.Entity(scene, entityID) for name, state in initialComponentStates.iteritems(): componentFactory = self.componentFactories.get(name, None) if componentFactory: component = componentFactory.CreateComponent(name, state) entity.AddComponent(name, component) else: self.LogWarn("I don't have a componentFactory for:", name, 'but I have these', ', '.join(self.__entitysystems__)) self.LogInfo('ClientEntityScene adding server entity: ', entity) scene.CreateAndRegisterEntity(entity)
async def on_request_tower(sid, data): # print("Tower requested: ", data) x, y, typ = data player = find_player(sid) cost = entities.TOWER_BUILD_COSTS[typ] castle_pos = castles[player.name].position_tuple() if cost <= player.cash and \ vec.is_within_bounds(castle_pos, (x, y), SPAWN_DISTANCE // 2): tower = entities.Entity(x, y, typ, player.name) board_add_entity(tower) towers[tower.uid] = (tower, 0) players[player.name].cash -= cost global towers_changed towers_changed = True await broadcast_message('entity_created', tower.to_list()) await broadcast_message('player_cash_changed', [player.name, player.cash]) else: print(player.name + ' cannot afford to build ' + typ + ' or tried to put the it somewhere illegal')
def ChangeState(lCurState, lNxtState, windView, EntManager, AstManager): """This function is passed a couple lists representing the info on the different levels of this game's hierarchical finite state machine. This function essentially generically sets up the Entity and Asset Managers based off of data that can be retreived from xml files. @param lCurState This list contains the information on which state the program is in and it takes acount into sub-states. So each element of the list is a sub-state of the previous element. @param lNxtState This list contains the information on which state the program is to be switched to and it takes acount into sub-states. So each element of the list is a sub-state of the previous element. @param windView This is SFML's View object and allows us to zoom in on the what would be shown in the window. This essentially just gives us the option to zoom in on the stuff visible for a certain state (can be specified in xml data.) @param EntManager This is the entity manager and is for loading entities into the game based on the state being switched to. The xml data tells which entities need to be loaded for what state. @param AstManager This is the asset manager and it is for loading in assets that are needed by entities. The xml data specifies what assets are to be fetched and used for the assembling of each entity. Once an asset is fetched once, it won't need to be loaded the second time because it's stored in the AstManager.""" print "NEW STATE!", lNxtState #The data will lie within the nextState[0]+".txt" file and the nextState[1] element within that elemthe ent. tree = parse("StateData/StateInit.xml") #The root element and the element containing the entities we need will be using this variable. root = tree.getroot() if root.find(lNxtState[0]) != None: #This changes the node to the one that represents the state we're switching to. root = root.find(lNxtState[0]).find(lNxtState[1]) if root == None: print "There was a problem finding %s in the StateInit.xml file." % ( lNxtState[1]) else: print "There was a problem finding %s in the StateInit.xml file." % ( lNxtState[0]) #This will reset the windowView's dimensions within the actual window with respect to the new state windView.reset(sf.FloatRect(int(int(root.find('viewWidth').text)//4), \ int(int(root.find('viewHeight').text)//4), \ int(int(root.find('viewWidth').text)//2), \ int(int(root.find('viewHeight').text)//2))) #This clears all of the things that in the game since the last state EntManager._Empty_Entity_Containers() AstManager._Empty_Assets() Input_Manager._Empty_Inputs() System_Manager._Empty_Systems() for entity in root.findall('Entity'): entityInstance = None #This checks to see if there is a function that exists that will assemble this entity. if entity.find('assembleFunc') != None: #This will hold all of the attributes needed to assemble the entity (using the xml files to get the data later on.) dEntityAttribs = {} #This will loop through all of the attribute names for each entity. for attrib in entity.find('Attributes').getiterator(): #Check to see if this is a sound for the entity! if attrib.tag == 'Sound': #THis will start a new list of Sounds if we haven't already loaded a sound into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = [] #Query the AssetManager for a sound that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag].append( AstManager._Get_Sound(attrib.attrib['name'])) elif attrib.tag == 'Music': #THis will start a new list of Musics if we haven't already loaded a sound into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = [] dEntityAttribs[attrib.tag].append( AstManager._Get_Music(attrib.attrib['name'])) #Check to see if this is a texture for the entitititity. elif attrib.tag == 'Texture': #THis will start a new list of Textures if we haven't already loaded a sound into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = [] #Query the AssetManager for a texture that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag].append( AstManager._Get_Texture(attrib.attrib['name'])) #Check to see if this is a font for the entitititity. elif attrib.tag == 'Font': #THis will start a new list of Fonts if we haven't already loaded a sound into this entity's attributes. if dEntityAttribs.get(attrib.tag, None) == None: dEntityAttribs[attrib.tag] = [] #Query the AssetManager for a font that is associated with this entity, then throw that into the dictionary of attributes! dEntityAttribs[attrib.tag].append( AstManager._Get_Font(attrib.attrib['name'])) else: #Anything else will just be put in the dictionary as an attribute dEntityAttribs[attrib.tag] = attrib.text module = importlib.import_module('entities') assembleFunc = getattr(module, entity.find('assembleFunc').text) #Here we're using the Assemble*() function associated with the name of this entity to assemble the entity so that #we can add it to the EntityManager. #And all Assemble*() functions will use the same arguments(using a dictionary to allow dynamic arguments.) entityInstance = assembleFunc(entity.attrib['name'], entity.attrib['type'], dEntityAttribs) else: #Here we will add in a default entity instance. entityInstance = entities.Entity(entity.attrib['name'], entity.attrib['type'], {}) #THis adds in the components that exist in the xml file for this entity (it allows custom/variations of entities to exist.) for component in entity.findall('Component'): #These are for getting the actual module = importlib.import_module('components') componentClass = getattr(module, component.attrib['name']) #This will add in a component into the entity we just created. #And note that it is giving the component a dictionary of the data in the xml files. entityInstance._Add_Component( componentClass({ DataTag.tag: DataTag.text for DataTag in component.getiterator() })) EntManager._Add_Entity(entityInstance) #Each one of these nodes will be an input that will be initialized for the state that is being loaded (and a multitude of kinds.) for inpoot in root.findall("Input"): #Check to see if this input's type is a hotspot. if inpoot.attrib["type"] == "hotspot": Input_Manager._Add_Hotspot(inpoot.find("x").text, inpoot.find("y").text, inpoot.find("width").text, inpoot.find("height").text, \ inpoot.find("OnPressed").find("type").text if inpoot.find("OnPressed") != None else None, \ inpoot.find("OnSelected").find("system").text if inpoot.find("OnSelected") != None else None, \ AssembleEntityInfo(inpoot, "OnSelected"), \ inpoot.find("OnDeselected").find("system").text if inpoot.find("OnDeselected") != None else None, \ AssembleEntityInfo(inpoot, "OnDeselected"), \ inpoot.find("OnPressed").find("system").text if inpoot.find("OnPressed") != None else None, \ AssembleEntityInfo(inpoot, "OnPressed"), \ inpoot.find("OnReleased").find("system").text if inpoot.find("OnReleased") != None else None, \ AssembleEntityInfo(inpoot, "OnReleased")) #Check to see if thisinput's type is a action. elif inpoot.attrib["type"] == "key": #This will add a key_Listener to our Input_Manager given the attribute data from the inpoot elemenet from the xml file. Input_Manager._Add_Key_Listener(inpoot.find("key").text, \ inpoot.find("OnPressed").find("type").text if inpoot.find("OnPressed") != None else None, \ inpoot.find("OnPressed").find("system").text if inpoot.find("OnPressed") != None else None, \ AssembleEntityInfo(inpoot, "OnPressed"), \ inpoot.find("OnReleased").find("system").text if inpoot.find("OnReleased") != None else None, \ AssembleEntityInfo(inpoot, "OnReleased")) elif inpoot.attrib["type"] == "mouse": pass #These are the systems that are relevant to this state and they will be added into the System_Queue class. for system in root.findall("System"): #This will load a system into the System_Queue and then it will be activated next update. systems.System_Queue._Add_System( system.find("type").text, system.find("system").text, AssembleEntityInfo(root)) #Now we gotta update the state variables so that we aren't signaling to change states anymore for i in xrange(len(lCurState)): lCurState[i] = lNxtState[i] lNxtState[i] = "NULL"
def test_pclink(self): agency1 = entities.Entity(**self.expect) agency2 = entities.Entity(**self.expect) agency1.pclink(agency1, agency2) assert agency2 in agency1.children() assert agency1 in agency2.parents()
def test_json(self): entity = entities.Entity(**self.expect) with self.assertRaises(NotImplementedError): entity.json()
def test_geometry(self): entity = entities.Entity(**self.expect) with self.assertRaises(NotImplementedError): entity.geometry()
def test_id(self): entity = entities.Entity(**self.expect) assert entity.id() is None
def test_name(self): entity = entities.Entity(**self.expect) assert entity.name() is None
def test_tariff_creation_localized_name(self): self.addCleanupDelete('tariff') info = entities.Tariff(self).generate() localized_long = entities.Entity(self).localized_name(True) localized_long.update({'en': self.generate_big_string()}) self.check_api_method(self.admin_client.tariff.create, ['localized_name'], info, localized_long)
import sys, os sys.path.append(os.getcwd()) import entities, viewer import numpy as np import importlib importlib.reload(entities) importlib.reload(viewer) cube = entities.Entity(node_color=(255, 255, 255), name="cube") cube_nodes = [(x, y, z) for x in (-75, 75) for y in (-75, 75) for z in (-75, 75)] cube.addNodes(np.array(cube_nodes)) cube.addEdges([(n, n + 4) for n in range(0, 4)]) cube.addEdges([(n, n + 1) for n in range(0, 8, 2)]) cube.addEdges([(n, n + 2) for n in (0, 1, 4, 5)]) plain = entities.Entity(node_color=(255, 255, 255), name="plane") plain_nodes = [(x, y, z) for x in (0, 150) for y in (0, 150) for z in (0, )] plain_edges = [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)] plain.addNodes(np.array(plain_nodes)) plain.addEdges(plain_edges) yes = viewer.Viewer(500, 500) yes.addObjects([cube, plain]) objects = ["context", "cube", "plane"] #buttons buttons = []
def CreateEntity(self, scene, entityID): newEntity = entities.Entity(scene, entityID) return newEntity
def test_init(self): agency = entities.Entity(**self.expect)
def test_children(self): self.test_add_child() entity = entities.Entity(**self.expect) assert not entity.children()
def test_parents(self): self.test_add_parent() entity = entities.Entity(**self.expect) assert not entity.parents()
def test_add_parent(self): agency1 = entities.Entity(**self.expect) agency2 = entities.Entity(**self.expect) agency2.add_parent(agency1) assert agency2 in agency1.children() assert agency1 in agency2.parents()
def test_get(self): agency = entities.Entity(**self.expect) for key in self.expect.keys(): assert agency.get(key) == self.expect.get(key) assert agency[key] == self.expect[key]
def test_service_create_localized_name(self): self.addCleanupDelete('service') info = entities.Service(self).generate() localized_long = entities.Entity(self).localized_name(True) localized_long.update({'en': self.generate_big_string()}) self.check_api_method(self.admin_client.service.create, ['localized_name'], info, localized_long)
def test_get_keyerror(self): agency = entities.Entity(**self.expect) with self.assertRaises(KeyError): agency['asdf']
def test_get_default(self): agency = entities.Entity(**self.expect) assert agency.get('asdf','test') == 'test'
def main(): pygame.init() screen = pygame.display.set_mode((1, 1)) Entity_list = [] select_coords = False selection = [] #main game loop while 1: #main menu main_menu() while 1: #event loop for event in pygame.event.get(): #quit game if event.type == QUIT: pygame.quit() sys.exit() #button press if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: #add Entity entity = entities.Entity([0, 0]) Entity_list.append(entity) print "{} created".format(entity.name) if event.key == pygame.K_2: #display entities if len(Entity_list) == 0: print "There are no entites" break print "Entity List:" print make_name_list(Entity_list) if event.key == pygame.K_3: #select entity if len(Entity_list) == 0: print "There are no entites" break else: name_list = make_name_list(Entity_list) choice = make_menu_choice("Select an entity", name_list) selection = Entity_list[choice - 1] print "{} selected".format(selection.name) if event.key == pygame.K_4: #display entity atributes if selection == []: print "No Entity Selected" break print "{}'s position is {}".format( selection.name, selection.pos) if event.key == pygame.K_5: #modify atributes if selection == []: print "No Entity Selected" break new_x = input("New x-coordinate: ") new_y = input("New y-coordinate: ") selection.pos = [new_x, new_y] if event.key == pygame.K_6: #reprint main menu main_menu() if event.key == pygame.K_7: #unselect entity selection = [] print "Deselected" if event.key == pygame.K_8: #exit pygame.quit() sys.exit() break
def test_setitem(self): agency = entities.Entity(**self.expect) agency.set('test', 'ok') assert agency['test'] == 'ok'
def new_entity(self, name): """Create a new entity to be used for this merge""" result = entities.Entity(self, name) return result
def setup(scene): InputHandler.set_key_bindings_default() """ max_iteration = 500 count = 0 entityNum = 1 min = 30 max = 50 while count < entityNum and max_iteration > 0: max_iteration -= 1 radius = random.randint(min, max) x = float(random.randint(radius, game_state.WIDTH/2 - radius)) y = float(random.randint(radius, game_state.HEIGHT/2 - radius)) if count % 2 == 0: sh = shape.Rectangle(radius, radius) else: sh = shape.Circle(radius/2) m = entities.Entity(x, y, sh) add = True m.move_component = component.PhysicsComponent(m, radius) for entity in scene.entities: if collision.check_collision(m, entity) is not False: add = False break if add: scene.entities.append(m) count += 1 """ width = 50 height = 50 pts = [ [+width / 2, -height / 2], # tr [+width / 2, +height / 2], # br [-width / 2, +height / 2], # bl [-width / 2, -height / 2], # tl ] pts1 = [ [+width / 2, -height / 2], # tr [0, +height / 1.5], # br [-width / 2, -height / 2], # tl ] entity = entities.Entity(1000, 100, pts1, 1.2) entity.input_component = components.PlayerInputComponent(entity) entity.render_component = components.PolygonRenderComponent(entity) #entity.render_component = components.CircleRenderComponent(entity, 10, 10) entity.move_component = components.MoveComponent(entity, 10) entity.components[components.CameraComponent] = components.CameraComponent( entity) #entity.components[components.GravityComponent] = components.GravityComponent(entity) entity.components[ components.FrictionComponent] = components.FrictionComponent( entity, 0.2) entity.components[ components.CollisionComponent] = components.CollisionComponent(entity) scene.add_to_entities(entity) entity = entities.Entity(200, 200, pts1) entity.input_component = components.SteeringBehaviorInputComponent(entity) entity.render_component = components.PolygonRenderComponent(entity) #entity.render_component = components.CircleRenderComponent(entity, 10, 2) entity.move_component = components.MoveComponent(entity, 10) #entity.components[components.GravityComponent] = components.GravityComponent(entity) entity.components[ components.FrictionComponent] = components.FrictionComponent( entity, 0.2) entity.components[ components.CollisionComponent] = components.CollisionComponent(entity) scene.add_to_entities(entity) ######################################################################################################## width = scene.width height = scene.height pts = [ [+width / 2, -height / 2], # tr [+width / 2, +height / 2], # br [-width / 2, +height / 2], # bl [-width / 2, -height / 2], # tl ] entity = entities.Entity(width / 2, height / 2, pts) entity.render_component = components.PolygonRenderComponent(entity) entity.render_component.fill = False scene.add_to_entities(entity) # tree = entities.create_tree() # tree.components.append(components.CameraComponent(tree)) # tree.input_component = components.PlayerInputComponent(tree) # scene.add_to_entities(tree) # count = count_entities(tree) # print(count) ######################################################################################################## y_pos = scene.height - 50 te = terrain.terrain_entity(50, scene.width, 0.1, 200, 200) te.pos[1] = y_pos te.pos[0] = te.bounding_radius() - 20 scene.add_to_entities(te)