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

Revision 473, 11.4 KB checked in by maximinus_parpg, 10 years ago (diff)

Added chewies patch to make parpg FIFE 0.3.0 compatible.
Thanks to the FIFE devs for all their work!
You now need FIFE 0.3.0 to run parpg.

  • Property svn:eol-style set to native
Line 
1#!/usr/bin/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 scripts import world
20from base import *
21from composed import *
22from scripts.inventory import Inventory
23
24"""All actors go here. Concrete classes only."""
25
26__all__ = ["PlayerCharacter", "NonPlayerCharacter",]
27
28TDS = Setting()
29_AGENT_STATE_NONE, _AGENT_STATE_IDLE, _AGENT_STATE_APPROACH, _AGENT_STATE_RUN, _AGENT_STATE_WANDER, _AGENT_STATE_TALK = xrange(6)
30
31class ActorBehaviour (fife.InstanceActionListener):
32    """Fife agent listener
33    """
34    def __init__(self, layer):
35        fife.InstanceActionListener.__init__(self)
36        self.layer = layer
37   
38    def attachToLayer(self, agent_ID):
39        """ Attaches to a certain layer
40            @type agent_ID: String
41            @param agent_ID: ID of the layer to attach to.
42            @return: None
43        """
44        self.agent = self.layer.getInstance(agent_ID)
45        self.agent.addActionListener(self)
46        self.state = _AGENT_STATE_NONE
47        self.speed = float(TDS.readSetting("PCSpeed"))-1 # TODO: rework/improve
48       
49    def getX(self):
50        """Get the NPC's x position on the map.
51           @rtype: integer"
52           @return: the x coordinate of the NPC's location"""
53        return self.agent.getLocation().getLayerCoordinates().x
54
55    def getY(self):
56        """Get the NPC's y position on the map.
57           @rtype: integer
58           @return: the y coordinate of the NPC's location"""
59        return self.agent.getLocation().getLayerCoordinates().y
60       
61    def onInstanceActionFinished(self, instance, action):
62        pass
63
64   
65class PCBehaviour (ActorBehaviour):
66    def __init__(self, parent = None, layer = None):
67        super(PCBehaviour, self).__init__(layer)
68       
69        self.parent = parent
70        self.idle_counter = 1
71        self.speed = float(TDS.readSetting("PCSpeed")) # TODO: rework/improve
72        self.nextAction = None
73        self.agent = None
74       
75    def onInstanceActionFinished(self, instance, action):
76        """@type instance: ???
77           @param instance: ???
78           @type action: ???
79           @param action: ???
80           @return: None"""
81       
82        # First we reset the next behavior
83        act = self.nextAction
84        self.nextAction = None 
85        self.idle()
86       
87        if act:
88            act.execute()
89           
90        if(action.getId() != 'stand'):
91            self.idle_counter = 1
92        else:
93            self.idle_counter += 1
94           
95    def onNewMap(self, layer):
96        """Sets the agent onto the new layer.
97        """
98        if self.agent is not None:
99            self.agent.removeActionListener(self)
100           
101        self.agent = layer.getInstance(self.parent.ID)
102        self.agent.addActionListener(self)
103        self.state = _AGENT_STATE_NONE
104        self.idle_counter = 1
105   
106    def idle(self):
107        """@return: None"""
108        self.state = _AGENT_STATE_IDLE
109        self.agent.act('stand', self.agent.getFacingLocation())
110
111class PlayerCharacter (GameObject, Living, CharStats):
112    """
113    PC class
114    """
115    def __init__ (self, ID, agent_layer = None, inventory = None, **kwargs):
116        GameObject.__init__( self, ID, **kwargs )
117        Living.__init__( self, **kwargs )
118        CharStats.__init__( self, **kwargs )
119
120        self.is_PC = True
121       
122        # PC _has_ an inventory, he _is not_ one
123        if inventory == None:
124            self.inventory = Inventory()
125            self.inventory.placeItem(CarryableItem(ID=456, name="Dagger123"))
126            self.inventory.placeItem(CarryableItem(ID=555, name="Beer"))
127        else:
128            self.inventory = inventory
129        self.peopleIknow = set()
130
131        self.state = _AGENT_STATE_NONE
132        self.layer_id = agent_layer.getId()
133        self.createBehaviour(agent_layer)
134   
135    def meet(self, npc):
136        """Record that the PC has met a certain NPC
137        @type npc: str
138        @param npc: The NPC's name or id"""
139        if npc in self.peopleIknow:
140            """raise RuntimeError("I already know %s" % npc)
141               we could raise an error here, but should probably be a warn"""
142            return
143        self.peopleIknow.add(npc)
144
145    def met(self, npc):
146        """Indicate whether the PC has met this npc before
147        @type npc: str
148        @param npc: The NPC's name or id
149        @return: None"""
150        return npc in self.peopleIknow
151
152    def createBehaviour(self, layer):
153        """Creates the behaviour for this actor.
154            @return None """
155        self.behaviour = PCBehaviour(self, layer)
156   
157    def setup(self):
158        """@return: None"""
159        self.behaviour.attachToLayer(self.ID)
160
161    def start(self):
162        """@return: None"""
163        self.behaviour.idle()
164   
165    def run(self, location):
166        """Makes the PC run to a certain location
167           @type location: fife.ScreenPoint
168           @param location: Screen position to run to.
169           @return: None"""
170        self.state = _AGENT_STATE_RUN
171        self.behaviour.nextAction = None
172        self.behaviour.agent.move('run', location, self.behaviour.speed+1)
173
174    def walk(self, location):
175        """Makes the PC walk to a certain location.
176           @type location: fife.ScreenPoint
177           @param location: Screen position to walk to.
178           @return: None"""
179        self.state = _AGENT_STATE_RUN
180        self.behaviour.nextAction = None 
181        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
182
183    def teleport(self, location):
184        """Teleports a PC instantly to the given location.
185           @type location: fife.Location
186           @param location: Target coordinates for PC.
187           @return: None"""
188        self.state = _AGENT_STATE_IDLE
189        self.behaviour.nextAction = None 
190        self.behaviour.agent.setLocation(location)
191
192    def approach(self, location, action = None):
193        """Approaches a location and then perform an action (if set).
194           @type loc: fife.Location
195           @param loc: the location to approach
196           @type action: Action
197           @param action: The action to schedule for execution after the approach.
198           @return: None"""
199        self.state = _AGENT_STATE_APPROACH
200        self.behaviour.nextAction = action
201        boxLocation = tuple([int(float(i)) for i in location])
202        l = fife.Location(self.behaviour.agent.getLocation())
203        l.setLayerCoordinates(fife.ModelCoordinate(*boxLocation))
204        self.behaviour.agent.move('run', l, self.behaviour.speed+1)
205
206
207class NPCBehaviour(ActorBehaviour):
208    def __init__(self, Parent = None, Layer = None):
209        super(NPCBehaviour, self).__init__(Layer)
210       
211        self.parent = Parent
212        self.state = _AGENT_STATE_NONE
213       
214        # hard code this for now
215        self.distRange = (2, 4)
216       
217    def getTargetLocation(self):
218        """@rtype: fife.Location
219           @return: NPC's position"""
220        x = self.getX()
221        y = self.getY()
222        if self.state == _AGENT_STATE_WANDER:
223            """ Random Target Location """
224            l = [0, 0]
225            for i in range(len(l)):
226                sign = randrange(0, 2)
227                dist = randrange(self.distRange[0], self.distRange[1])
228                if sign == 0:
229                    dist *= -1
230                l[i] = dist
231            x += l[0]
232            y += l[1]
233            # Random walk is
234            # rl = randint(-1, 1);ud = randint(-1, 1);x += rl;y += ud
235        l = fife.Location(self.agent.getLocation())
236        l.setLayerCoordinates(fife.ModelCoordinate(x, y))
237        return l
238
239    def onInstanceActionFinished(self, instance, action):
240        """What the NPC does when it has finished an action.
241           Called by the engine and required for InstanceActionListeners.
242           @type instance: fife.Instance
243           @param instance: self.agent (the NPC listener is listening for this
244            instance)
245           @type action: ???
246           @param action: ???
247           @return: None"""
248        if self.state == _AGENT_STATE_WANDER:
249            self.target_loc = self.getTargetLocation()
250        self.idle()
251       
252   
253    def idle(self):
254        """Controls the NPC when it is idling. Different actions
255           based on the NPC's state.
256           @return: None"""
257        if self.state == _AGENT_STATE_NONE:
258            self.state = _AGENT_STATE_IDLE
259            self.agent.act('stand', self.agent.getFacingLocation())
260        elif self.state == _AGENT_STATE_IDLE:
261            self.target_loc = self.getTargetLocation()
262            self.state = _AGENT_STATE_WANDER
263            self.agent.act('stand', self.agent.getFacingLocation())
264        elif self.state == _AGENT_STATE_WANDER:
265            self.parent.wander(self.target_loc)
266            self.state = _AGENT_STATE_NONE
267        elif self.state == _AGENT_STATE_TALK:
268            self.agent.act('stand', self.pc.getLocation())
269
270class NonPlayerCharacter(GameObject, Living, Scriptable, CharStats):
271    """
272    NPC class
273    """
274    def __init__(self, ID, agent_layer=None, name='NPC', \
275                 text = 'A nonplayer character', inventory = None, **kwargs):
276        # init game object
277        GameObject.__init__(self, ID, name=name, **kwargs)
278        Living.__init__(self, **kwargs)
279        Scriptable.__init__(self, **kwargs)
280        CharStats.__init__(self, **kwargs)
281
282        self.is_NPC = True
283        if inventory == None:
284            self.inventory = Inventory()
285        else:
286            self.inventory = inventory
287        self.layer_id = agent_layer.getId()
288        self.createBehaviour(agent_layer)       
289        self.dialogue = kwargs.get('dialogue')
290
291    def createBehaviour(self, layer):
292        """ Creates the behaviour for this actor.
293            @return None """
294        self.behaviour = NPCBehaviour(self, layer)
295
296    def getLocation(self):
297        """ Get the NPC's position as a fife.Location object. Basically a
298            wrapper.
299            @rtype: fife.Location
300            @return: the location of the NPC"""
301        return self.behaviour.agent.getLocation()
302   
303    def wander(self, location):
304        """Nice slow movement for random walking.
305           @type location: fife.Location
306           @param location: Where the NPC will walk to.
307           @return: None"""
308        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
309
310    def run(self, location):
311        """Faster movement than walk.
312           @type location: fife.Location
313           @param location: Where the NPC will run to."""
314        self.behaviour.agent.move('run', location, self.behaviour.speed+1)
315
316    def talk(self, pc):
317        """ Makes the NPC ready to talk to the PC
318            @return: None"""
319        self.behaviour.state = _AGENT_STATE_TALK
320        self.behaviour.pc = pc.behaviour.agent
321        self.behaviour.idle()
322   
323    def setup(self):
324        """@return: None"""
325        self.behaviour.attachToLayer(self.ID)
326
327    def start(self):
328        """@return: None"""
329        self.behaviour.idle()
Note: See TracBrowser for help on using the repository browser.