changeset 61:2727d6b78978

Implemented creation of dynamic entities.
author KarstenBock@gmx.net
date Sun, 18 Sep 2011 16:26:12 +0200
parents e2004c9549d7
children bf63da4b27f5
files behaviours/base.py behaviours/moving.py entities/__init__.py entities/character.py gamemodel.py
diffstat 5 files changed, 48 insertions(+), 155 deletions(-) [+]
line wrap: on
line diff
--- a/behaviours/base.py	Sun Sep 18 16:07:07 2011 +0200
+++ b/behaviours/base.py	Sun Sep 18 16:26:12 2011 +0200
@@ -59,7 +59,6 @@
     def idle(self):
         """@return: None"""
         self.state = _AGENT_STATE_IDLE
-        self.agent.act('stand', self.agent.getFacingLocation())       
         
     def onInstanceActionFinished(self, instance, action):
         """@type instance: ???
--- a/behaviours/moving.py	Sun Sep 18 16:07:07 2011 +0200
+++ b/behaviours/moving.py	Sun Sep 18 16:26:12 2011 +0200
@@ -57,6 +57,11 @@
         else:
             self.idle_counter += 1 
         
+    def idle(self):
+        """@return: None"""
+        BaseBehaviour.idle(self)
+        self.agent.act('stand', self.agent.getFacingLocation())    
+        
     def run(self, location):
         """Makes the PC run to a certain location
            @type location: fife.ScreenPoint
--- a/entities/__init__.py	Sun Sep 18 16:07:07 2011 +0200
+++ b/entities/__init__.py	Sun Sep 18 16:26:12 2011 +0200
@@ -14,40 +14,27 @@
 #   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
 
 import sys
-import character
-
-ENTITIES = [character.Character]
 
-def getAllEntities ():
-    """Returns a dictionary with the names of the entity classes
-       mapped to the classes themselves"""
-    result = {}
-    for entity in ENTITIES:
-        result[entity.__name__] = entity
-    return result
+from parpg.bGrease import Entity
 
-def createEntity(info, extra = None):
+def createEntity(info, world, extra = None):
     """Called when we need to get an actual object.
        @type info: dict
        @param info: stores information about the object we want to create
        @type extra: dict
        @param extra: stores additionally required attributes
        @return: the object"""
-    # First, we try to get the type and world, which every game_obj needs.
+    # First, we try to get the world, which every game_obj needs.
     extra = extra or {}
-    try:
-        ent_type = info.pop('type')
-        world = info.pop('world')
-    except KeyError:
-        sys.stderr.write("Error: Game object missing type or world.")
-        sys.exit(False)
 
     # add the extra info
     for key, val in extra.items():
-        info[key] = val
+        info[key].update(val)
 
     # this is for testing purposes
-    try:
-        return getAllEntities()[ent_type](world, **info)
-    except KeyError:
-        return None
+    new_ent = Entity(world)
+    for component, data in info.items():
+        comp_obj = getattr(new_ent, component)
+        for key, value in data.items():
+            setattr(comp_obj, key, value)
+    return new_ent
--- a/entities/character.py	Sun Sep 18 16:07:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-#   This program is free software: you can redistribute it and/or modify
-#   it under the terms of the GNU General Public License as published by
-#   the Free Software Foundation, either version 3 of the License, or
-#   (at your option) any later version.
-
-#   This program is distributed in the hope that it will be useful,
-#   but WITHOUT ANY WARRANTY; without even the implied warranty of
-#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#   GNU General Public License for more details.
-
-#   You should have received a copy of the GNU General Public License
-#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
-
-from bGrease import Entity
-from bGrease.geometry import Vec2d
-
-class Character(Entity):
-    def __init__(self, world, view_name, real_name, desc, statistics, max_bulk,
-                 identifier, layer=None, behaviour=None, dialogue=None, 
-                 gfx=None, items=None
-                 ):
-        self.characterstats.statistics = statistics
-        
-        self.description.view_name = view_name
-        self.description.real_name = real_name
-        self.description.desc = desc
-        
-        self.dialogue.dialogue = dialogue
-        
-        self.container.children = items or []
-        self.container.max_bulk = max_bulk
-        
-        self.fifeagent.identifier = identifier
-        self.fifeagent.layer = layer
-        self.fifeagent.behaviour = behaviour
-        self.fifeagent.gfx = gfx
--- a/gamemodel.py	Sun Sep 18 16:07:07 2011 +0200
+++ b/gamemodel.py	Sun Sep 18 16:26:12 2011 +0200
@@ -98,20 +98,15 @@
                                           self.engine.getVFS() 
                                           )
 
-    def checkAttributes(self, attributes):
+    def checkAttributes(self, attributes, template):
         """Checks for attributes that where not given in the map file
         and fills them with values from the object database
-        @param attributes: attributes to check
+        @param attributes: attributes to check        
         @type attributes: Dictionary
+        @param template: Template from which the values will be used
         @return: The modified attributes""" 
-        if attributes.has_key("object_type"):
-            class_name = attributes.pop("object_type")
-        else:
-            class_name = attributes["type"]
-        if not attributes.has_key("type"):
-            attributes["type"] = class_name
-        if self.object_db.has_key(class_name):
-            db_attributes = deepcopy(self.object_db[class_name])
+        if self.object_db.has_key(template):
+            db_attributes = deepcopy(self.object_db[template])
             for key in db_attributes.keys():
                 if attributes.has_key(key):
                     attributes[key] = attributes[key] or db_attributes[key]
@@ -158,7 +153,6 @@
         # create the extra data
         extra = {}
         extra['controller'] = self
-        attributes = self.checkAttributes(attributes)
         
         info = {}
         info.update(attributes)
@@ -386,14 +380,11 @@
         agent[unique_agent_id] = agent_values
         self.agents[namespace].update(agent)
         object_model = ""
-        if agent_values.has_key("ObjectModel"): 
-            object_model =  agent_values["ObjectModel"]
-        elif agent_values["ObjectType"] == "MapItem":
-            object_data = self.object_db[agent_values["ItemType"]]
-            object_model = object_data["gfx"] if object_data.has_key("gfx") \
-                        else "generic_item"
+        if agent_values["Entity"].has_key("fifeagent") \
+           and agent_values["Entity"]["fifeagent"].has_key("gfx"): 
+            object_model = agent_values["Entity"]["fifeagent"]["gfx"]
         else:
-            object_model = self.object_db[agent_values["ObjectType"]]["gfx"]
+            object_model = self.object_db[agent_values["Template"]]["fifeagent"]["gfx"]
         import_file = self.agent_import_files[object_model]
         loadImportFile(self.obj_loader, import_file, self.engine)
         
@@ -454,17 +445,12 @@
             new_map.load(map_file)    
 
     def createAgent(self, agent, inst_id, world):
-        object_type = agent["ObjectType"]
-        object_id = agent["ObjectModel"] \
-                                if agent.has_key("ObjectModel") \
-                                else None
-        if object_id == None:
-            if object_type == "MapItem":
-                object_data = self.object_db[agent["ItemType"]]
-                object_id = object_data["gfx"] if object_data.has_key("gfx") \
-                            else "generic_item"
-            else:
-                object_id = self.object_db[object_type]["gfx"]
+        entity_data = agent["Entity"]
+        if agent.has_key("Template"):
+            entity_data = self.checkAttributes(entity_data, agent["Template"])
+        object_id = agent["Entity"]["fifeagent"]["gfx"] \
+                                if agent["Entity"]["fifeagent"].has_key("gfx") \
+                                else "generic_item"
         map_obj = self.fife_model.getObject(str(object_id), "PARPG")
         if not map_obj:
             logging.warning("Object with inst_id={0}, ns=PARPG, "
@@ -474,7 +460,6 @@
         x_pos = agent["Position"][0]
         y_pos = agent["Position"][1]
         z_pos = agent["Position"][2] if len(agent["Position"]) == 3 \
-                                        else -0.1 if object_type == "MapItem" \
                                         else 0.0  
         stack_pos = agent["Stackposition"] if \
                         agent.has_key("StackPosition") \
@@ -496,65 +481,19 @@
 
         if (map_obj.getAction('default')):
             target = fife.Location(self.active_map.agent_layer)
-            inst.act('default', target, True)
+            inst.act('default', target, True)        
+
             
-        inst_dict = {}
-        inst_dict["identifier"] = inst_id
-        inst_dict["world"]= world
-        inst_dict["type"] = object_type
-        inst_dict["gfx"] = object_id
-        if agent.has_key("Open"):
-            inst_dict["is_open"] = parseBool(agent["Open"])
-        if agent.has_key("Locked"):
-            inst_dict["locked"] = parseBool(agent["Locked"])
-        if agent.has_key("ViewName"):
-            inst_dict["view_name"] = agent["ViewName"]
-            inst_dict["real_name"] = agent["RealName"] \
-                     if agent.has_key("RealName") else agent["ViewName"]
-        if agent.has_key("Text"):
-            inst_dict["desc"] = agent["Text"]
+        entity_data["fifeagent"]["identifier"] = inst_id
+        if entity_data["fifeagent"].has_key("behaviour"):
+            entity_data["fifeagent"]["behaviour"] = getattr(behaviours, entity_data["fifeagent"]["behaviour"])()
+        else:
+            entity_data["fifeagent"]["behaviour"] = behaviours.Base()
         if self.dialogues.has_key(inst_id):
-            inst_dict["dialogue"] = self.dialogues[inst_id]
-        if agent.has_key("TargetMap"):
-            inst_dict["target_map_name"] = agent["TargetMap"]
-        if agent.has_key("TargetPosition"):
-            inst_dict["target_x"] = agent["TargetPosition"][0]
-            inst_dict["target_y"] = agent["TargetPosition"][1]
-        if agent.has_key("Inventory"):
-            #TODO: Fix setting of inventory
-            #inventory = Inventory()
-            #inventory_objs = agent["Inventory"]
-            #for inventory_obj in inventory_objs:
-            #    self.createInventoryObject(inventory,
-            #                               inventory_obj 
-            #                               )
-            #inst_dict["inventory"] = inventory
-            pass
-
-        if agent.has_key("Items"):
-            container_objs = agent["Items"]
-            #TODO: Create inventory items
-            items = []#self.createContainerItems(container_objs)
-            inst_dict["items"] = items
-            
-        if agent.has_key("ItemType"):
-            if not agent.has_key("item"):
-                item_data = {}
-                item_data["type"] = agent["ItemType"]
-                item_data["ID"] = inst_id 
-                #TODO item_data = self.createContainerObject(item_data)
-            else:
-                item_data = agent["item"]
-            inst_dict["item"] = item_data
-            inst_dict["item_type"] = agent["ItemType"]
-        if agent.has_key("Behaviour"):
-            inst_dict["behaviour"] = getattr(behaviours, agent["Behaviour"])()
-        #TODO: Add real statistics and bulk
-        if object_type == "Character":
-            inst_dict["statistics"] = {}
-            inst_dict["max_bulk"] = 100
-
-        self.createMapObject(self.active_map.agent_layer, inst_dict)
+            entity_data["dialogue"] = {}
+            entity_data["dialogue"]["dialogue"] = self.dialogues[inst_id]
+        
+        self.createMapObject(self.active_map.agent_layer, entity_data, world)
     
     def placeAgents(self, world):
         """Places the current maps agents """
@@ -618,7 +557,7 @@
         self.active_map.makeActive()
         self.game_state.current_map_name = map_name
 
-    def createMapObject (self, layer, attributes):
+    def createMapObject (self, layer, attributes, world):
         """Create an object and add it to the current map.
            @type layer: fife.Layer
            @param layer: FIFE layer object exists in
@@ -630,13 +569,12 @@
         # create the extra data
         extra = {}
         if layer is not None:
-            extra['layer'] = layer
-        attributes = self.checkAttributes(attributes)
+            extra['fifeagent'] = {}
+            extra['fifeagent']['layer'] = layer
         
-        obj_type = attributes["type"]
-        obj = createEntity(attributes, extra)
+        obj = createEntity(attributes, world, extra)
         if obj:
-            self.addObject(layer, obj, obj_type) 
+            self.addObject(layer, obj) 
 
     def addPC(self, layer, player_char):
         """Add the PlayerCharacter to the map
@@ -655,7 +593,7 @@
         self.game_state.getObjectById("PlayerCharacter").fifeagent.behaviour.speed = self.settings.parpg.PCSpeed
 
 
-    def addObject(self, layer, obj, obj_type):
+    def addObject(self, layer, obj):
         """Adds an object to the map.
            @type layer: fife.Layer
            @param layer: FIFE layer object exists in
@@ -675,7 +613,7 @@
             obj.fifeagent.pos.Y = ref.Y
             obj.fifeagent.gfx = ref.gfx  
              
-        if obj_type == "Character":
+        if obj.fifeagent.behaviour:
             obj.fifeagent.behaviour.parent = obj
             fifeagent.setup_behaviour(obj.fifeagent)
             obj.fifeagent.behaviour.speed = self.settings.parpg.PCSpeed