1

我目前正在用 Python 制作游戏。每当您在游戏中需要帮助时,只需输入帮助,您就可以阅读帮助部分。

唯一的问题是,我需要为每个级别添加一个功能块。

def level_01():
    choice = raw_input('>>>: ')
    if choice=='help':
        level_01_help()


def level_012():
    choice = raw_input('>>>: ')
    if choice=='help':
        level_02_help()

所以我想知道是否可以为所有级别制作一个全局功能块?当你输入 help 时,你会进入 help(),然后它会自动返回到你刚刚来自的功能块。

我真的希望你明白我的意思,我真的很感激我能得到的所有帮助。

4

4 回答 4

4

您实际上可以将帮助函数作为参数传递,这意味着您的代码可以变为:

def get_choice(help_func):
    choice = raw_input('>>>: ')
    if choice == 'help':
        help_func()
    else:
        return choice

def level_01():
    choice = get_choice(level_01_help)

def level_02():
    choice = get_choice(level_02_help)

理想情况下,您应该为所有与界面相关的任务有一个单独的模块,这样游戏和界面将是两个独立的实体。这应该使那些 2911 行更加清晰,如果您决定更改接口(例如从命令行到 Tkinter 或 Pygame),您将有一个更容易的时间。只是我的 2¢

于 2013-08-07T23:48:37.640 回答
4

处理此类问题的一个非常好的方法是使用内置的 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']
于 2013-08-08T01:09:24.580 回答
1

当然,总有可能一概而论。但是由于您提供的信息很少(并假设“帮助”是唯一常见的功能),原始代码非常简单。我不会为了每个级别节省 1 行代码而牺牲这个属性。

于 2013-08-08T00:06:24.000 回答
1

更好的解决方案是将您所在的级别存储为变量,并让帮助函数处理所有帮助内容。

例子:

def help(level):
    # do whatever helpful stuff goes here
    print "here is the help for level", level

def level(currentLevel):
    choice = raw_input('>>>: ')
    if choice=='help':
        help(currentLevel)
    if ...: # level was beaten
        level(currentLevel + 1) # move on to the next one
于 2013-08-07T23:47:45.370 回答