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

Revision 276, 9.7 KB checked in by orlandov, 10 years ago (diff)

Ticket #67: Refactor unit tests into runnable shape

  • Move tests to their own top level directory
  • Fix unit test failures
  • Add base/composed classes to test suite
  • Run like "nosetests ./run_python.py" OR "./run_python.py"
  • 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        if self.trueAttr ('scriptable'):
126            self.runScript('onOpen')
127           
128    def close(self):
129        """Opens the object, and runs an 'onClose' script, if present"""
130        self.is_open = False
131        if self.trueAttr ('scriptable'):
132            self.runScript('onClose')             
133       
134class Lockable (Openable):
135    """Allows objects to be locked"""
136    def __init__ (self, locked = True, **kwargs):
137        """Init operation for lockable objects
138        @type locked: Boolean
139        @param locked: Keyword boolen argument to set the initial locked state.
140        """
141        self.is_lockable = True
142        self.locked = locked
143        Openable.__init__( self, **kwargs )
144       
145    def unlock (self):
146        """Handles unlocking functionality"""
147        self.locked = False     
148       
149    def lock (self):
150        """Handles  locking functionality"""
151        self.close()
152        self.locked = True
153       
154    def open (self, *args, **kwargs):
155        """Adds a check to see if the object is unlocked before running the
156           .open() function of the parent class"""
157        if self.locked:
158            raise ValueError ("Open failed: object locked")
159        super (Lockable,self).open(*args,**kwargs)
160       
161class Carryable (object):
162    """Allows objects to be stored in containers"""
163    def __init__ (self, **kwargs):
164        self.is_carryable = True
165        self.in_container = None
166        self.weight = 1.0
167   
168class Container (object):
169    """Gives objects the capability to hold other objects"""
170    def __init__ (self, **kwargs):
171        self.is_container = True
172        self.items = []
173       
174    def placeItem (self, item):
175        """Adds the provided carriable item to the inventory.
176           Runs an 'onStoreItem' script, if present"""   
177        if not item.trueAttr ('carryable'):
178            raise ValueError ('% is not carriable!' % item)
179        item.in_container = self
180        self.items.append (item)
181        # Run any scripts associated with storing an item in the container
182        if self.trueAttr ('scriptable'):
183            self.runScript('onPlaceItem')
184       
185    def takeItem (self, item):
186        """Takes the listed item out of the inventory.
187           Runs an 'ontakeItem' script"""       
188        if not item in self.items:
189            raise ValueError ('I do not contain this item: %s' % item)
190        self.items.remove (item)
191        # Run any scripts associated with popping an item out of the container
192        if self.trueAttr ('scriptable'):
193            self.runScript('ontakeItem')
194       
195class Inventory (object):
196    """Aggregate class for things that have multiple Containers"""
197    def __init__ (self, **kwargs):
198        self.is_inventory = True
199        self.containers = []
200   
201class Living (object):
202    def __init__ (self, **kwargs):
203        self.is_living = True
204    def die(self):
205        self.is_living = False
206       
207class Scriptable (object):
208    """Allows objects to have predefined scripts executed on certain events"""
209    def __init__ (self, scripts = {}, **kwargs):
210        """Init operation for scriptable objects
211           @type scripts: Dictionary
212           @param scripts: Dictionary where the event strings are keys. The
213           values are 3-item tuples (function, positional_args, keyword_args)"""
214        self.is_scriptable = True
215        self.scripts = scripts
216       
217    def runScript (self, event):
218        """Runs the script for the given event"""
219        if event in self.scripts and self.scripts[event]:
220            func, args, kwargs = self.scripts[event]
221            func (*args, **kwargs)
222           
223    def setScript (self, event, func, args = [] , kwargs={}):
224        """Sets a script to be executed for the given event."""
225        self.scripts[event] = (func, args, kwargs)
226
227class CharStats (object):
228    """Provides the object with character statistics"""
229    def __init__ (self, **kwargs):
230        self.is_charstats = True
231       
232class Wearable (object):
233    def __init__ (self, **kwargs):
234        """Allows the object to be weared somewhere on the body (e.g. pants)"""
235        self.is_wearable = True
236   
237class Usable (object):
238    """Allows the object to be used in some way (e.g. a Zippo lighter
239       to make a fire)"""
240    def __init__ (self, **kwargs):
241        self.is_usable = True
242       
243class Weapon (object):
244    """Allows the object to be used as a weapon"""
245    def __init__ (self, **kwargs):
246        self.is_weapon = True
247       
248class Destructable (object):
249    """Allows the object to be destroyed"""
250    def __init__ (self, **kwargs):
251        self.is_destructable = True
252       
253class Trappable (object):
254    """Provides trap slots to the object"""
255    def __init__ (self, **kwargs):
256        self.is_trappable = True
Note: See TracBrowser for help on using the repository browser.