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

Revision 295, 9.2 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #103: Patch by Elie De Brauwer, Added possibility to make the player character run, this can be toggled with the run console command, comment[s:trac, t:103]

  • 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/>.
17import fife
18from scripts import world
19from base import *
20
21"""All actors go here. Concrete classes only."""
22
23__all__ = ["PlayerCharacter", "NonPlayerCharacter",]
24
25TDS = Setting()
26_AGENT_STATE_NONE, _AGENT_STATE_IDLE, _AGENT_STATE_APPROACH, _AGENT_STATE_RUN, _AGENT_STATE_WANDER, _AGENT_STATE_TALK = xrange(6)
27
28class ActorBehaviour (fife.InstanceActionListener):
29    """Fife agent listener
30    """
31    def __init__(self, Layer):
32        fife.InstanceActionListener.__init__(self)
33        self.layer = Layer
34   
35    def attachToLayer(self, agentID):
36        # init listener
37        self.agent = self.layer.getInstance(agentID)
38        self.agent.addActionListener(self)
39        self.state = _AGENT_STATE_NONE
40        self.speed = float(TDS.readSetting("PCSpeed"))-1 # TODO: rework/improve
41       
42    def getX(self):
43        """Get the NPC's x position on the map.
44           @rtype: integer"
45           @return: the x coordinate of the NPC's location"""
46        return self.agent.getLocation().getLayerCoordinates().x
47
48    def getY(self):
49        """Get the NPC's y position on the map.
50           @rtype: integer
51           @return: the y coordinate of the NPC's location"""
52        return self.agent.getLocation().getLayerCoordinates().y
53       
54    def onInstanceActionFinished(self, instance, action):
55        pass
56
57   
58class PCBehaviour (ActorBehaviour):
59    def __init__(self, Parent = None, Layer = None):
60        super(PCBehaviour, self).__init__(Layer)
61       
62        self.parent = Parent
63        self.idlecounter = 1
64        self.speed = float(TDS.readSetting("PCSpeed")) # TODO: rework/improve
65        self.nextAction = None
66       
67    def onInstanceActionFinished(self, instance, action):
68        """@type instance: ???
69           @param instance: ???
70           @type action: ???
71           @param action: ???
72           @return: None"""
73        if self.nextAction:
74            self.nextAction.execute()
75            self.nextAction = None
76            self.idle()
77        else:
78            self.idle()
79           
80        if(action.getId() != 'stand'):
81            self.idlecounter = 1
82        else:
83            self.idlecounter += 1
84           
85    def onNewMap(self, layer):
86        """Sets the agent onto the new layer.
87        """
88        self.agent = layer.getInstance(self.parent.name)
89        self.agent.addActionListener(self)
90        self.state = _AGENT_STATE_NONE
91        self.idlecounter = 1
92   
93    def idle(self):
94        """@return: None"""
95        self.state = _AGENT_STATE_IDLE
96        self.agent.act('stand', self.agent.getFacingLocation())
97
98class PlayerCharacter (GameObject, Living, CharStats):
99    """
100    PC class
101    """
102    def __init__ (self, ID, agent_layer = None, **kwargs):
103        GameObject.__init__( self, ID, **kwargs )
104        Living.__init__( self, **kwargs )
105        CharStats.__init__( self, **kwargs )
106
107        self.is_PC = True
108       
109        # PC _has_ an inventory, he _is not_ one
110        self.inventory = None
111       
112        self.state = _AGENT_STATE_NONE
113        self.behaviour = PCBehaviour(self, agent_layer)
114   
115    def setup(self):
116        """@return: None"""
117        self.behaviour.attachToLayer(self.ID)
118
119    def start(self):
120        """@return: None"""
121        self.behaviour.idle()
122   
123    def run(self, location):
124        """Makes the PC run to a certain location
125           @type location: fife.ScreenPoint
126           @param location: Screen position to run to.
127           @return: None"""
128        self.state = _AGENT_STATE_RUN
129        self.behaviour.agent.move('run', location, self.behaviour.speed+1)
130
131    def walk(self, location):
132        """Makes the PC walk to a certain location.
133           @type location: fife.ScreenPoint
134           @param location: Screen position to walk to.
135           @return: None"""
136        self.state = _AGENT_STATE_RUN
137        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
138     
139    def approach(self, location, action = None):
140        """Approaches an npc and then ???.
141           @type loc: fife.Location
142           @param loc: the location to approach
143           @type action: Action
144           @param action: The action to schedule for execution after the approach.
145           @return: None"""
146        self.state = _AGENT_STATE_APPROACH
147        self.behaviour.nextAction = action
148        boxLocation = tuple([int(float(i)) for i in location])
149        l = fife.Location(self.behaviour.agent.getLocation())
150        l.setLayerCoordinates(fife.ModelCoordinate(*boxLocation))
151        self.behaviour.agent.move('run', l, self.behaviour.speed)
152
153class NPCBehaviour(ActorBehaviour):
154    def __init__(self, Parent = None, Layer = None):
155        super(NPCBehaviour, self).__init__(Layer)
156       
157        self.parent = Parent
158        self.state = _AGENT_STATE_NONE
159       
160        # hard code this for now
161        self.distRange = (2, 4)
162       
163    def getTargetLocation(self):
164        """@rtype: fife.Location
165           @return: NPC's position"""
166        x = self.getX()
167        y = self.getY()
168        if self.state == _AGENT_STATE_WANDER:
169            """ Random Target Location """
170            l = [0, 0]
171            for i in range(len(l)):
172                sign = randrange(0, 2)
173                dist = randrange(self.distRange[0], self.distRange[1])
174                if sign == 0:
175                    dist *= -1
176                l[i] = dist
177            x += l[0]
178            y += l[1]
179            # Random walk is
180            # rl = randint(-1, 1);ud = randint(-1, 1);x += rl;y += ud
181        l = fife.Location(self.agent.getLocation())
182        l.setLayerCoordinates(fife.ModelCoordinate(*tuple([x, y])))
183        return l
184
185    def onInstanceActionFinished(self, instance, action):
186        """What the NPC does when it has finished an action.
187           Called by the engine and required for InstanceActionListeners.
188           @type instance: fife.Instance
189           @param instance: self.agent (the NPC listener is listening for this
190            instance)
191           @type action: ???
192           @param action: ???
193           @return: None"""
194        if self.state == _AGENT_STATE_WANDER:
195            self.targetLoc = self.getTargetLocation()
196        self.idle()
197       
198   
199    def idle(self):
200        """Controls the NPC when it is idling. Different actions
201           based on the NPC's state.
202           @return: None"""
203        if self.state == _AGENT_STATE_NONE:
204            self.state = _AGENT_STATE_IDLE
205            self.agent.act('stand', self.agent.getFacingLocation())
206        elif self.state == _AGENT_STATE_IDLE:
207            self.targetLoc = self.getTargetLocation()
208            self.state = _AGENT_STATE_WANDER
209            self.agent.act('stand', self.agent.getFacingLocation())
210        elif self.state == _AGENT_STATE_WANDER:
211            self.parent.wander(self.targetLoc)
212            self.state = _AGENT_STATE_NONE
213        elif self.state == _AGENT_STATE_TALK:
214            self.agent.act('stand', self.pc.getLocation())
215
216class NonPlayerCharacter(GameObject, Living, Scriptable, CharStats):
217    """
218    NPC class
219    """
220    def __init__(self, ID, agent_layer = None, name = 'NPC', \
221                 text = 'A nonplayer character', **kwargs):
222        # init game object
223        GameObject.__init__( self, ID, **kwargs )
224        Living.__init__( self, **kwargs )
225        Scriptable.__init__( self, **kwargs )
226        CharStats.__init__( self, **kwargs )
227
228        self.is_NPC = True
229        self.inventory = None
230       
231        self.behaviour = NPCBehaviour(self, agent_layer)
232
233    def getLocation(self):
234        """ Get the NPC's position as a fife.Location object. Basically a
235            wrapper.
236            @rtype: fife.Location
237            @return: the location of the NPC"""
238        return self.behaviour.agent.getLocation()
239   
240    def wander(self, location):
241        """Nice slow movement for random walking.
242           @type location: fife.Location
243           @param location: Where the NPC will walk to.
244           @return: None"""
245        self.behaviour.agent.move('walk', location, self.behaviour.speed-1)
246
247    def run(self, location):
248        """Faster movement than walk.
249           @type location: fife.Location
250           @param location: Where the NPC will run to."""
251        self.behaviour.agent.move('run', location, self.behaviour.speed+1)
252
253    def talk(self, pc):
254        """ Makes the NPC ready to talk to the PC
255            @return: None"""
256        self.behaviour.state = _AGENT_STATE_TALK
257        self.behaviour.pc = pc.behaviour.agent
258        self.behaviour.idle()
259   
260    def setup(self):
261        """@return: None"""
262        self.behaviour.attachToLayer(self.ID)
263
264    def start(self):
265        """@return: None"""
266        self.behaviour.idle()
Note: See TracBrowser for help on using the repository browser.