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

Revision 315, 9.6 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #2: Patch by eliedebrauwer. Performed some cleanup on scripts/common and scripts/objects. comment[s:trac, t:66]

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