Created
October 25, 2013 22:12
-
-
Save damianesteban/7162621 to your computer and use it in GitHub Desktop.
OOP "Weapon Class" for text-based game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Weapon(object): | |
def __init__(self, name): | |
self.name = name | |
self.parent = None | |
def destroy(self): | |
if self.parent: | |
self.parent.weaponDestroyed() | |
def WeaponRef(): | |
def getWeapon(self): | |
return self._weapon | |
def setWeapon(self, newWeapon): | |
if newWeapon == None: #ensure that this is a valid weapon | |
delWeapon(self) | |
return | |
if hasattr(self, "weapon"): #remove old weapon's reference to us | |
self._weapon.parent = None | |
self._weapon = newWeapon | |
newWeapon.parent = self | |
def delWeapon(self): | |
if hasattr(self, "weapon"): | |
self._weapon.parent = None | |
del self._weapon | |
return property(getWeapon, setWeapon, delWeapon) | |
class Parent(object): | |
weapon = WeaponRef() | |
def __init__(self, name, weapon=None): | |
self.name = name | |
self.weapon = weapon | |
def weaponDestroyed(self): | |
print "%s deleting reference to %s" %(self.name, self.weapon.name) | |
del self.weapon | |
w1 = Weapon("weapon 1") | |
w2 = Weapon("weapon 2") | |
w3 = Weapon("weapon 3") | |
p1 = Parent("parent 1", w1) | |
p2 = Parent("parent 2") | |
w1.destroy() | |
p2.weapon = w2 | |
w2.destroy() | |
p2.weapon = w3 | |
w3.destroy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment