source: trunk/game/scripts/objects/base.py @ 284

Revision 284, 9.8 KB checked in by b0rland_parpg, 10 years ago (diff)

Ticket #67: patch by b0rland

  • Added GPL headers to test scripts
  • Added descriptions to test methods
  • Added the try/except guard to Openable class where it accesses GameObject?'s method (being overcautious)
  • Added tests for Openable class
  • Renamed some more test classes to match the naming convention
  • 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
18"""Containes classes defining the base properties of all interactable in-game
19   objects (such as Carryable, Openable, etc. These are generally independent
20   classes, which can be combined in almost any way and order.
21
22   Some rules that should be followed when CREATING base property classes:
23   
24   1. If you want to support some custom initialization arguments, always define
25      them as keyword ones. Only GameObject would use positional arguments.
26   2. In __init__() **ALWAYS** call the parent's __init__(**kwargs), preferably
27      *at the end* of your __init__() (makes it easier to follow)
28   3. There should always be an is_x class member set to True on __init__
29      (where X is the name of the class)
30
31   EXAMPLE:
32
33   class Openable(object):
34       def __init__ (self, is_open = True, **kwargs):
35           self.is_openable = True
36           self.is_open = is_open
37           super(Openable,self).__init__ (**kwargs)
38       
39
40   Some rules are to be followed when USING the base classes to make composed ones:
41
42   1. The first parent should always be the base GameObject class
43   2. Base classes other than GameObject can be inherited in any order
44   3. The __init__ functoin of the composed class should always invoke the
45      parent's __init__() *before* it starts customizing any variables.
46
47   EXAMPLE:
48
49   class TinCan (GameObject, Container, Scriptable, Destructable, Carryable):
50       def __init__ (self, *args, **kwargs):
51           super(TinCan,self).__init__ (*args, **kwargs)
52           self.name = 'Tin Can'"""
53import fife
54from settings import Setting
55from random import randrange
56
57class GameObject (object):
58    """A base class to be inherited by all game objects. This must be the
59       first class (left to right) inherited by any game object."""
60    def __init__ (self, ID, gfx = {}, xpos = 0.0, ypos = 0.0, map_id = None, 
61                  blocking=True, name="Generic object", text="Item description",
62                  desc="Detailed description", **kwargs):
63        """Set the basic values that are shared by all game objects.
64           @type ID: String
65           @param ID: Unique object identifier. Must be present.
66           @type gfx: Dictionary
67           @param gfx: Dictionary with graphics for the different contexts       
68           @type coords 2-item tuple
69           @param coords: Initial coordinates of the object.
70           @type map_id: ???
71           @param map_id: Identifier of the map where the object is located
72           @type blocking: Boolean
73           @param blocking: Whether the object blocks character movement
74           @type name: String
75           @param name: The display name of this object (e.g. 'Dirty crate')
76           @type text: String
77           @param text: A longer description of the item
78           @type desc: String
79           @param desc: A long description of the item that is displayed when it is examined
80           """
81       
82        self.ID = ID
83        self.gfx = gfx
84        self.X = xpos
85        self.Y = ypos
86        self.map_id = map_id
87        self.blocking = True
88        self.name = name
89        self.text = text
90        self.desc = desc
91       
92    def trueAttr(self, attr):
93        """Shortcut function to check if the current object has a member named
94           is_%attr and if that attribute evaluates to True"""
95        return hasattr(self,'is_%s' % attr) and getattr(self, 'is_%s' % attr)
96
97    def _getCoords(self):
98        """Get-er property function"""
99        return (self.X, self.Y)
100   
101    def _setCoords(self, coords):
102        """Set-er property function"""
103        self.X, self.Y = float(coords[0]), float (coords[1])
104       
105    coords = property (_getCoords, _setCoords, 
106        doc = "Property allowing you to get and set the obejct's coordinates via tuples")
107   
108    def __repr__(self):
109        """A debugging string representation of the object"""
110        return "<%s:%s>" % (self.name, self.ID)
111
112class Openable(object):
113    """Adds open() and .close() capabilities to game objects
114    The current state is tracked by the .is_open variable"""
115    def __init__(self, is_open = True, **kwargs):
116        """Init operation for openable objects
117        @type is_open: Boolean
118        @param is_open: Keyword boolean argument sets the initial state."""
119        self.is_openable = True
120        self.is_open = is_open
121   
122    def open(self):
123        """Opens the object, and runs an 'onOpen' script, if present"""
124        self.is_open = True
125        try:
126            if self.trueAttr ('scriptable'):
127                self.runScript('onOpen')
128        except AttributeError :
129            pass
130           
131    def close(self):
132        """Opens the object, and runs an 'onClose' script, if present"""
133        self.is_open = False
134        try:
135            if self.trueAttr ('scriptable'):
136                self.runScript('onClose')
137        except AttributeError :
138            pass
139class Lockable (Openable):
140    """Allows objects to be locked"""
141    def __init__ (self, locked = True, **kwargs):
142        """Init operation for lockable objects
143        @type locked: Boolean
144        @param locked: Keyword boolen argument to set the initial locked state.
145        """
146        self.is_lockable = True
147        self.locked = locked
148        Openable.__init__( self, **kwargs )
149       
150    def unlock (self):
151        """Handles unlocking functionality"""
152        self.locked = False     
153       
154    def lock (self):
155        """Handles  locking functionality"""
156        self.close()
157        self.locked = True
158       
159    def open (self, *args, **kwargs):
160        """Adds a check to see if the object is unlocked before running the
161           .open() function of the parent class"""
162        if self.locked:
163            raise ValueError ("Open failed: object locked")
164        super (Lockable,self).open(*args,**kwargs)
165       
166class Carryable (object):
167    """Allows objects to be stored in containers"""
168    def __init__ (self, **kwargs):
169        self.is_carryable = True
170        self.in_container = None
171        self.weight = 1.0
172   
173class Container (object):
174    """Gives objects the capability to hold other objects"""
175    def __init__ (self, **kwargs):
176        self.is_container = True
177        self.items = []
178       
179    def placeItem (self, item):
180        """Adds the provided carriable item to the inventory.
181           Runs an 'onStoreItem' script, if present"""   
182        if not item.trueAttr ('carryable'):
183            raise ValueError ('% is not carriable!' % item)
184        item.in_container = self
185        self.items.append (item)
186        # Run any scripts associated with storing an item in the container
187        if self.trueAttr ('scriptable'):
188            self.runScript('onPlaceItem')
189       
190    def takeItem (self, item):
191        """Takes the listed item out of the inventory.
192           Runs an 'ontakeItem' script"""       
193        if not item in self.items:
194            raise ValueError ('I do not contain this item: %s' % item)
195        self.items.remove (item)
196        # Run any scripts associated with popping an item out of the container
197        if self.trueAttr ('scriptable'):
198            self.runScript('ontakeItem')
199       
200class Inventory (object):
201    """Aggregate class for things that have multiple Containers"""
202    def __init__ (self, **kwargs):
203        self.is_inventory = True
204        self.containers = []
205   
206class Living (object):
207    def __init__ (self, **kwargs):
208        self.is_living = True
209    def die(self):
210        self.is_living = False
211       
212class Scriptable (object):
213    """Allows objects to have predefined scripts executed on certain events"""
214    def __init__ (self, scripts = {}, **kwargs):
215        """Init operation for scriptable objects
216           @type scripts: Dictionary
217           @param scripts: Dictionary where the event strings are keys. The
218           values are 3-item tuples (function, positional_args, keyword_args)"""
219        self.is_scriptable = True
220        self.scripts = scripts
221       
222    def runScript (self, event):
223        """Runs the script for the given event"""
224        if event in self.scripts and self.scripts[event]:
225            func, args, kwargs = self.scripts[event]
226            func (*args, **kwargs)
227           
228    def setScript (self, event, func, args = [] , kwargs={}):
229        """Sets a script to be executed for the given event."""
230        self.scripts[event] = (func, args, kwargs)
231
232class CharStats (object):
233    """Provides the object with character statistics"""
234    def __init__ (self, **kwargs):
235        self.is_charstats = True
236       
237class Wearable (object):
238    def __init__ (self, **kwargs):
239        """Allows the object to be weared somewhere on the body (e.g. pants)"""
240        self.is_wearable = True
241   
242class Usable (object):
243    """Allows the object to be used in some way (e.g. a Zippo lighter
244       to make a fire)"""
245    def __init__ (self, **kwargs):
246        self.is_usable = True
247       
248class Weapon (object):
249    """Allows the object to be used as a weapon"""
250    def __init__ (self, **kwargs):
251        self.is_weapon = True
252       
253class Destructable (object):
254    """Allows the object to be destroyed"""
255    def __init__ (self, **kwargs):
256        self.is_destructable = True
257       
258class Trappable (object):
259    """Provides trap slots to the object"""
260    def __init__ (self, **kwargs):
261        self.is_trappable = True
Note: See TracBrowser for help on using the repository browser.