Lilgam é um pequeno jogo (literalmente, uma reducão forçada de "Litle Game") que usei de cobaia pro
PyLint, uma maravilhosa ferramenta por sinal. Agora estou usando de cobaia pra testar o
PythonToHtml do
PedroWerneck.Update: Na hora de postar as identações nã ficam como eui queria, era pra estar com 4 espaços. Mas fica assim mesmo por enquanto...
#!/usr/bin/python
"""A litle game.
"""
# 0.1: Add CoAdj and Objs to Places
# Implement "todo methods"
# Make Objs effectively "usable"
__revision__ = "0.0.6"
__autor__ = "Eduardo de Oliveira Padoan (eduardo.padoan@gmail.com)"
__licence__ = "GNU GPL"
class Place:
"""A single place in the map game.
"""
def __init__(self, name, descr, obj=False, coadj=None):
self.name = name
self.descr = descr
#3 bodies dont occupy the same space...
if obj:
self.obj = Obj(obj)
elif coadj is not None:
self.coadj = Coadj(coadj)
else:
self.coadj = coadj
def __repr__(self):
return self.name
class Obj:
"""An usable object in the game.
"""
def __init__(self, name, objtype='', pwr=0):
self.name = name
self.objtype = objtype # 'eatable' ou 'weapon', in the future
self.pwr = pwr
def __repr__(self):
return self.name
class Person:
"""Any person in the game,
be it a Hero or a CoAdj,
share this commom ancestral.
"""
def __init__(self, name):
self._pwr = 10
self.dead = False
self.name = name
def __repr__(self):
return self.name
def gethurtby(self, attacker):
"""To be called by an "Attacker".
Automatically counter attack the Attacker.
"""
if self.pwr > 0:
self.pwr -= 1
# counter-attack
attacker.gethurtby(self)
def _set_pwr(self, value):
"""Set the Persons' Power
"""
self._pwr = value
if self._pwr == 0:
self.dead = True
def _get_pwr(self):
"""Get the Persons' Power
"""
return self._pwr
pwr = property(_set_pwr, _get_pwr, doc="The Persons' Power!")
class Coadj(Person):
"""Any Person on the game that is not the Hero.
"""
def __init__(self, name, pwr=10):
Person.__init__(self, name)
self.pwr = pwr
### XXX This section (the game map) should be in a separeted module.
### So, various maps can be done.
aav_ms_c = Place('Acacia Av./Morgue St. Cross', '...')
aav_s = Place('Acacia Av., block 2', '...')
aav_n = Place('Acacia Av., block 1', '...')
mst_e = Place('Morgue St,, block 2', '...')
mst_w = Place('Morgue St., block 1', '...')
## local n s e w
places = {aav_ms_c: (aav_n, aav_s, mst_e, mst_w),
aav_n: (None, aav_ms_c, None, None),
aav_s: (aav_ms_c, None, None, None),
mst_e: (None, None, None, aav_ms_c),
mst_w: (None, None, aav_ms_c, None)}
###
class CantDoItError(Exception):
"""Hero cant do something.
Can Be:
- Too much items already.
- The hero is at a dead-end.
- No one to attack.
"""
pass
class TheresAlreadyAHero(Exception):
"""There Should be only 1 Chosen One
"""
pass
class GameOverError(Exception):
"""Game Over, baby.
"""
pass
class Hero(Person):
"""The hero of the game!
"""
theres_a_hero = False
def __init__(self, name):
Person.__init__(self, name)
self.objs = []
self.place = aav_ms_c
self.weapon = None
self._pts = 0 # points - use self.pts (see 'properties' near the end)
self.lvl = 1 # level
if Hero.theres_a_hero:
raise TheresAlreadyAHero
else:
Hero.theres_a_hero = True # yes, the class, not the instance
def go_to(self, goto):
"""Take the Hero to a place.
0 = N, 1 = S, 2 = E, 3 = W
"""
goto = {'n': 0, 's': 1, 'e': 2, 'w': 3}[goto]
next_step = places[self.place][goto]
if next_step is not None:
self.place = next_step
print "\nYou are in %s" % (self.place)
else:
raise CantDoItError
def grab(self):
"""Grab an object an out it in the inventory.
"""
if len(self.objs) == 10:
raise CantDoItError
self.objs.append(self.place.obj)
del self.place.obj
if len(self.objs) == 1:
self.weapon = self.objs[0]
def change_obj(self):
"""Change the object at hand.
"""
self.objs.append(self.weapon)
self.weapon = self.objs[0]
del self.objs[0]
def drop_obj(self):
"""Drop the object at hand.
"""
self.place.obj = self.weapon
self.weapon = self.objs[0]
del self.objs[0]
def attack(self):
"""Attack (takes 1 power point) a CoAdj
present in the local you are.
"""
if self.place.coadj is None:
raise CantDoItError
elif self.dead:
raise GameOverError # dead in combat
else:
self.place.coadj.gethurtby(self)
if self.place.coadj.dead:
self.pts += 1
del self.place.coadj
def describe(self):
"""Shows the description of your location.
"""
print "\nYou are in %s" % (self.place)
print self.place.descr
def inventory(self):
""" Show the Hero inventory (objects, power, points and level)
"""
if self.weapon is not None:
print '{'+self.weapon+'}'
if len(self.objs) > 0:
for obj in self.objs:
print obj + '\n'
else:
print "\nYou don't have anything."
print '\nlevel: %s' % (self.lvl)
print '\npoints: %s' % (self.pts)
### XXX TODO methods:
def eat(self):
"""Eat the food you find.
To be implemented.
"""
pass
def help_me(self):
"""Show the game help.
"""
pass
def open_this(self):
"""Open something. (doors, boxes...)
To be implemented.
"""
pass
### properties:
def _set_pts(self, value):
"""Sets the hero points.
Increment the level if the new point total
are divisable by 10.
"""
self._pts = value
if (self._pts % 10) == 0:
self.lvl += 1
self._pts *= 10
print "\nCongratulations!\nNow you are at level %s" % (self.lvl)
def _get_pts(self):
"""Get the hero points.
"""
return self._pts
pts = property(_get_pts, _set_pts, doc="The hero points")
def main(heroname, prompt='>>> '):
"""Main game function.
Call it when ready to play.
"""
hero = Hero(heroname)
cont = True
def end():
""" End the game.
To be used in the dict ahead.
"""
raise GameOverError
commands = {'go': hero.go_to,
'q': end,
'op': hero.open_this,
'gb': hero.grab,
'at': hero.attack,
'ds': hero.describe,
'ch': hero.change_obj,
'do': hero.drop_obj,
'et': hero.eat,
'in': hero.inventory,
'?': hero.help_me}
while cont:
# command parsing
com = raw_input(prompt).lower().strip(' ').split(' ')
com, arg = (len(com) == 2) and com or (com[0], None)
try:
if com:
if arg is not None:
commands[com](arg)
else:
commands[com]()
except (KeyError, ValueError): # inexistent com, wrong number of args.
print '\nCommand not understood. See ? for help.'
except CantDoItError:
print '\nYou cant do it. See ? for help.'
except GameOverError:
print '\nYou are Dead. Bye.'
cont = False
if __name__ == "__main__":
main("Foo B. Quux")