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

Revision 213, 9.0 KB checked in by tZee_parpg, 11 years ago (diff)

#71 Applied Jason's patch to fix issues with Python 2.6 + fixed the issue for the WoodenCrate?, too.

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