source: trunk/game/scripts/objects/actors.py @ 590

Revision 590, 14.5 KB checked in by beliar, 10 years ago (diff)

Patch by Beliar.

  • Property svn:eol-style set to native
Line 
1#!/usr/bin/env python
2
3#   This file is part of PARPG.
4
5#   PARPG is free software: you can redistribute it and/or modify
6#   it under the terms of the GNU General Public License as published by
7#   the Free Software Foundation, either version 3 of the License, or
8#   (at your option) any later version.
9
10#   PARPG is distributed in the hope that it will be useful,
11#   but WITHOUT ANY WARRANTY; without even the implied warranty of
12#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13#   GNU General Public License for more details.
14
15#   You should have received a copy of the GNU General Public License
16#   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
17
18from fife import fife
19from base import GameObject, Living, Scriptable, CharStats
20from fife.extensions.fife_settings import Setting
21from composed import CarryableItem
22from scripts.inventory import Inventory
23from random import randrange
24
25"""All actors go here. Concrete classes only."""
26
27__all__ = ["PlayerCharacter", "NonPlayerCharacter",]
28
29TDS = Setting(app_name="PARPG",
30              settings_file="./settings.xml", 
31              settings_gui_xml="")
32_AGENT_STATE_NONE, _AGENT_STATE_IDLE, _AGENT_STATE_APPROACH, _AGENT_STATE_RUN, _AGENT_STATE_WANDER, _AGENT_STATE_TALK = xrange(6)
33
34class ActorBehaviour (fife.InstanceActionListener):
35    """Fife agent listener"""
36    def __init__(self, layer):
37        fife.InstanceActionListener.__init__(self)
38        self.layer = layer
39        self.agent = None
40        self.state = None
41        self.speed = 0
42        self.idle_counter = 1
43   
44    def attachToLayer(self, agent_ID):
45        """Attaches to a certain layer
46           @type agent_ID: String
47           @param agent_ID: ID of the layer to attach to.
48           @return: None"""
49        self.agent = self.layer.getInstance(agent_ID)
50        self.agent.addActionListener(self)
51        self.state = _AGENT_STATE_NONE
52        # TODO: rework/improve
53        self.speed = TDS.get("PARPG", "PCSpeed")-1
54       
55    def getX(self):
56        """Get the NPC's x position on the map.
57           @rtype: integer"
58           @return: the x coordinate of the NPC's location"""
59        return self.agent.getLocation().getLayerCoordinates().x
60
61    def getY(self):
62        """Get the NPC's y position on the map.
63           @rtype: integer
64           @return: the y coordinate of the NPC's location"""
65        return self.agent.getLocation().getLayerCoordinates().y
66       
67    def onNewMap(self, layer):
68        """Sets the agent onto the new layer."""
69        if self.agent is not None:
70            self.agent.removeActionListener(self)
71           
72        self.agent = layer.getInstance(self.parent.ID)
73        self.agent.addActionListener(self)
74        self.state = _AGENT_STATE_NONE
75        self.idle_counter = 1
76   
77    def idle(self):
78        """@return: None"""
79        self.state = _AGENT_STATE_IDLE
80        self.agent.act('stand', self.agent.getFacingLocation())
81
82    def onInstanceActionFinished(self, instance, action):
83        pass
84
85class PCBehaviour (ActorBehaviour):
86    def __init__(self, parent = None, layer = None):
87        super(PCBehaviour, self).__init__(layer)       
88        self.parent = parent
89        self.idle_counter = 1
90        # TODO: rework/improve
91        self.speed = TDS.get("PARPG", "PCSpeed")
92        self.nextAction = None
93        self.agent = None
94       
95    def onInstanceActionFinished(self, instance, action):
96        """@type instance: ???
97           @param instance: ???
98           @type action: ???
99           @param action: ???
100           @return: None"""
101        # First we reset the next behavior
102        act = self.nextAction
103        self.nextAction = None 
104        self.idle()
105       
106        if act:
107            act.execute()
108           
109        if(action.getId() != 'stand'):
110            self.idle_counter = 1
111        else:
112            self.idle_counter += 1           
113
114
115class NPCBehaviour(ActorBehaviour):
116    def __init__(self, Parent = None, Layer = None):
117        super(NPCBehaviour, self).__init__(Layer)
118       
119        self.parent = Parent
120        self.state = _AGENT_STATE_NONE
121        self.pc = None
122        self.target_loc = None
123        self.nextAction = None
124       
125        # hard code this for now
126        self.distRange = (2, 4)
127       
128    def getTargetLocation(self):
129        """@rtype: fife.Location
130           @return: NPC's position"""
131        x = self.getX()
132        y = self.getY()
133        if self.state == _AGENT_STATE_WANDER:
134            """ Random Target Location """
135            l = [0, 0]
136            for i in range(len(l)):
137                sign = randrange(0, 2)
138                dist = randrange(self.distRange[0], self.distRange[1])
139                if sign == 0:
140                    dist *= -1
141                l[i] = dist
142            x += l[0]
143            y += l[1]
144            # Random walk is
145            # rl = randint(-1, 1);ud = randint(-1, 1);x += rl;y += ud
146        l = fife.Location(self.agent.getLocation())
147        l.setLayerCoordinates(fife.ModelCoordinate(x, y))
148        return l
149
150    def onInstanceActionFinished(self, instance, action):
151        """What the NPC does when it has finished an action.
152           Called by the engine and required for InstanceActionListeners.
153           @type instance: fife.Instance
154           @param instance: self.agent (the NPC listener is listening for this
155                                        instance)
156           @type action: ???
157           @param action: ???
158           @return: None"""
159        if self.state == _AGENT_STATE_WANDER:
160            self.target_loc = self.getTargetLocation()
161        self.idle()
162       
163   
164    def idle(self):
165        """Controls the NPC when it is idling. Different actions
166           based on the NPC's state.
167           @return: None"""
168        if self.state == _AGENT_STATE_NONE:
169            self.state = _AGENT_STATE_IDLE
170            self.agent.act('stand', self.agent.getFacingLocation())
171        elif self.state == _AGENT_STATE_IDLE:
172            self.target_loc = self.getTargetLocation()
173            self.state = _AGENT_STATE_WANDER
174            self.agent.act('stand', self.agent.getFacingLocation())
175        elif self.state == _AGENT_STATE_WANDER:
176            self.parent.wander(self.target_loc)
177            self.state = _AGENT_STATE_NONE
178        elif self.state == _AGENT_STATE_TALK:
179            self.agent.act('stand', self.pc.getLocation())
180           
181class CharacterBase(GameObject, Living, CharStats):
182    """Base class for Characters"""
183    def __init__(self, ID, agent_layer = None, inventory = None, 
184                 text = "", **kwargs):
185        GameObject.__init__( self, ID, text = text, **kwargs )
186        Living.__init__( self, **kwargs )
187        CharStats.__init__( self, **kwargs )
188       
189        self.behaviour = None
190       
191        if inventory == None:
192            self.inventory = Inventory()
193        else:
194            self.inventory = inventory
195
196        self.state = _AGENT_STATE_NONE
197        self.layer_id = agent_layer.getId()
198        self.createBehaviour(agent_layer)
199   
200    def createBehaviour(self, layer):
201        """Creates the behaviour for this actor.
202           @return: None"""
203        pass
204   
205    def setup(self):
206        """@return: None"""
207        self.behaviour.attachToLayer(self.ID)
208
209    def start(self):
210        """@return: None"""
211        self.behaviour.idle()
212
213    def teleport(self, location):
214        """Teleports a Character instantly to the given location.
215           @type location: fife.Location
216           @param location: Target coordinates for Character.
217           @return: None"""
218        self.state = _AGENT_STATE_IDLE
219        self.behaviour.nextAction = None 
220        self.behaviour.agent.setLocation(location)
221
222    def hasItem(self, item_id):
223        """Returns wether an item is present in the players inventory or not
224        @param item_id: ID of the item
225        @type item_id: str
226        @return: True when the item is present, False when not"""
227        return self.inventory.findItem(item_id = item_id)
228
229    def itemCount(self, item_id = ""):
230        """Returns number of all items or items specified by item_id
231        the player has.
232        @param item_id: ID of the item, can be empty
233        @type item_id: str
234        @return: Number of items"""
235        return self.inventory.count(item_id)
236
237    def getLocation(self):
238        """Get the NPC's position as a fife.Location object. Basically a
239           wrapper.
240           @rtype: fife.Location
241           @return: the location of the NPC"""
242        return self.behaviour.agent.getLocation()
243   
244    def run(self, location):
245        """Makes the PC run to a certain location
246           @type location: fife.ScreenPoint
247           @param location: Screen position to run to.
248           @return: None"""
249        self.state = _AGENT_STATE_RUN
250        self.behaviour.nextAction = None
251        self.behaviour.agent.move('run', location, self.behaviour.speed+1)
252
253    def walk(self, location):
254        """Makes the PC walk to a certain location.
255           @type location: fife.ScreenPoint
256           @param location: Screen position to walk to.
257           @return: None"""
258        self.state = _AGENT_STATE_RUN
259        self.behaviour.nextAction = None 
260        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
261
262    def getStateForSaving(self):
263        """Returns state for saving
264        """
265        ret_dict = GameObject.getStateForSaving(self)
266        ret_dict["Inventory"] = self.inventory.serializeInventory()
267        return ret_dict
268
269    def _getCoords(self):
270        """Get-er property function"""
271        return (self.getLocation().getMapCoordinates().x, 
272                self.getLocation().getMapCoordinates().y)
273   
274    def _setCoords(self, coords):
275        """Set-er property function"""
276        map_coords = self.getLocation().getMapCoordinates()
277        map_coords.X, map_coords.Y = float(coords[0]), float (coords[1])
278        self.teleport(map_coords)
279   
280    coords = property (_getCoords, _setCoords, 
281        doc = "Property allowing you to get and set the object's \
282                coordinates via tuples")
283           
284class PlayerCharacter (CharacterBase):
285    """PC class"""
286    def __init__ (self, ID, agent_layer = None, inventory = None, 
287                  text = "Its you. Who would've thought that?", **kwargs):
288        if inventory == None:
289            inventory = Inventory()
290            inventory.placeItem(CarryableItem(ID=456, name="Dagger123"))
291            inventory.placeItem(CarryableItem(ID=555, name="Beer"))
292            inventory.placeItem(CarryableItem(ID = 616,
293                                    name = "Pamphlet",
294                                    image = "/gui/inv_images/inv_pamphlet.png"))
295        CharacterBase.__init__(self, ID, agent_layer, inventory, text, **kwargs)
296        self.people_i_know = set()
297        self.is_PC = True
298 
299    def getStateForSaving(self):
300        """Returns state for saving
301        """
302        ret_dict = super(PlayerCharacter, self).getStateForSaving()
303        ret_dict["PeopleKnown"] = self.people_i_know
304        return ret_dict
305   
306    def meet(self, npc):
307        """Record that the PC has met a certain NPC
308           @type npc: str
309           @param npc: The NPC's name or id"""
310        if npc in self.people_i_know:
311            # we could raise an error here, but should probably be a warn
312            # raise RuntimeError("I already know %s" % npc)
313            return
314        self.people_i_know.add(npc)
315
316    def met(self, npc):
317        """Indicate whether the PC has met this npc before
318           @type npc: str
319           @param npc: The NPC's name or id
320           @return: None"""
321        return npc in self.people_i_know
322
323    def createBehaviour(self, layer):
324        """Creates the behaviour for this actor.
325           @return: None"""
326        self.behaviour = PCBehaviour(self, layer)
327 
328    def approach(self, location, action = None):
329        """Approaches a location and then perform an action (if set).
330           @type loc: fife.Location
331           @param loc: the location to approach
332           @type action: Action
333           @param action: The action to schedule for execution after the approach.
334           @return: None"""
335        self.state = _AGENT_STATE_APPROACH
336        self.behaviour.nextAction = action
337        boxLocation = tuple([int(float(i)) for i in location])
338        l = fife.Location(self.behaviour.agent.getLocation())
339        l.setLayerCoordinates(fife.ModelCoordinate(*boxLocation))
340        self.behaviour.agent.move('run', l, self.behaviour.speed+1)
341   
342class NonPlayerCharacter(CharacterBase, Scriptable):
343    """NPC class"""
344    def __init__(self, ID, agent_layer=None, name='NPC', \
345                 text = 'A nonplayer character', inventory = None, 
346                 real_name = 'NPC', dialogue = None, **kwargs):
347        # init game object
348        CharacterBase.__init__(self, ID, agent_layer = agent_layer, 
349                               inventory = inventory, name=name, 
350                               real_name=real_name, text = text, **kwargs)
351        Scriptable.__init__(self, **kwargs)
352
353        self.is_NPC = True
354        self.dialogue = dialogue
355
356    def prepareStateForSaving(self, state):
357        """Prepares state for saving
358        @type state: dictionary
359        @param state: State of the object 
360        """
361        CharacterBase.prepareStateForSaving(self, state)
362        del state["behaviour"]
363
364    def getStateForSaving(self):
365        """Returns state for saving
366        """
367        ret_dict = CharacterBase.getStateForSaving(self)
368        ret_dict["Lives"] = self.is_living
369        ret_dict["State"] = self.behaviour.state
370        return ret_dict
371
372    def createBehaviour(self, layer):
373        """Creates the behaviour for this actor.
374           @return None """
375        self.behaviour = NPCBehaviour(self, layer)
376
377    def wander(self, location):
378        """Nice slow movement for random walking.
379           @type location: fife.Location
380           @param location: Where the NPC will walk to.
381           @return: None"""
382        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
383
384    def talk(self, pc):
385        """Makes the NPC ready to talk to the PC
386           @return: None"""
387        self.behaviour.state = _AGENT_STATE_TALK
388        self.behaviour.pc = pc.behaviour.agent
389        self.behaviour.idle()
390       
391    def give (self, item, actor):
392        """Gives the specified item to the different actor. Raises an exception if the item was invalid or not found
393           @type item: Carryable
394           @param item: The item object to give
395           @param actor: Person to give item to"""
396        if item == None: 
397            raise ValueError("I don't have %s" % item.name)
398        self.inventory.takeItem(item)
399        actor.inventory.placeItem(item)           
Note: See TracBrowser for help on using the repository browser.