Created
October 8, 2013 05:40
-
-
Save damianesteban/6879972 to your computer and use it in GitHub Desktop.
More examples of OOP text-based game classes in Python
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
rom collections import defaultdict | |
_items = defaultdict(set) | |
_owner = {} | |
class CanHaveItems(object): | |
@property | |
def items(self): | |
return iter(_items[self]) | |
def take(self, item): | |
item.change_owner(self) | |
def lose(self, item): | |
""" local cleanup """ | |
class _nobody(CanHaveItems): | |
def __repr__(self): | |
return '_nobody' | |
_nobody = _nobody() | |
class Destroyed(object): | |
def __repr__(self): | |
return 'This is an ex-item!' | |
class Item(object): | |
def __new__(cls, *a, **k): | |
self = object.__new__(cls) | |
_owner[self] = _nobody | |
_items[_nobody].add(self) | |
self._damage = .0 | |
return self | |
def destroy(self): | |
self.change_owner(_nobody) | |
self.__class__ = Destroyed | |
@property | |
def damage(self): | |
return self._damage | |
@damage.setter | |
def damage(self, value): | |
self._damage = value | |
if self._damage >= 1.: | |
self.destroy() | |
def change_owner(self, new_owner): | |
old_owner = _owner[self] | |
old_owner.lose(self) | |
_items[old_owner].discard(self) | |
_owner[self] = new_owner | |
_items[new_owner].add(self) | |
class Ball(Item): | |
def __init__(self, color): | |
self.color = color | |
def __repr__(self): | |
return 'Ball(%s)' % self.color | |
class Player(CanHaveItems): | |
def __init__(self, name): | |
self.name = name | |
def __repr__(self): | |
return 'Player(%s)' % self.name | |
ball = Ball('red') | |
ball = Ball('blue') | |
joe = Player('joe') | |
jim = Player('jim') | |
print list(joe.items), ':', list(jim.items) | |
joe.take(ball) | |
print list(joe.items), ':', list(jim.items) | |
jim.take(ball) | |
print list(joe.items), ':', list(jim.items) | |
print ball, ':', _owner[ball], ':', list(jim.items) | |
ball.damage += 2 | |
print ball, ':', _owner[ball], ':', list(jim.items) | |
print _items, ':', _owner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment