处理此类问题的一个非常好的方法是使用内置的 python 帮助。如果将文档字符串添加到函数中,它们将存储在函数对象的一个特殊属性中,称为doc。您可以通过如下代码找到它们:
def example():
'''This is an example'''
print example.__doc__
>> This is an example
you can get to them in code the same way:
def levelOne():
'''It is a dark and stormy night. You can look for shelter or call for help'''
choice = raw_input('>>>: ')
if choice=='help':
return levelOne.__doc__
这样做是保持代码和内容之间关系更清晰的好方法(尽管纯粹主义者可能会反对这意味着你不能使用 python 内置的帮助功能来编写程序员到程序员的文档)
我认为从长远来看,你可能会发现关卡想要成为类,而不是函数——这样你就可以存储状态(有人在关卡 1 中找到了密钥吗?是关卡 2 中的怪物还活着)并最大限度地重用代码. 粗略的轮廓是这样的:
class Level(object):
HELP = 'I am a generic level'
def __init__(self, name, **exits):
self.Name = name
self.Exits = exits # this is a dictionary (the two stars)
# so you can have named objects pointing to other levels
def prompt(self):
choice = raw_input(self.Name + ": ")
if choice == 'help':
self.help()
# do other stuff here, returning to self.prompt() as long as you're in this level
return None # maybe return the name or class of the next level when Level is over
def help(self):
print self.HELP
# you can create levels that have custom content by overriding the HELP and prompt() methods:
class LevelOne (Level):
HELP = '''You are in a dark room, with one door to the north.
You can go north or search'''
def prompt(self):
choice = raw_input(self.Name + ": ")
if choice == 'help':
self.help() # this is free - it's defined in Level
if choice == 'go north':
return self.Exits['north']