如何在Python中调用可以调用不同函数的通用函数调用?

时间:2011-11-12 20:06:34

标签: python python-2.7

我试图在Python中制作基于文本的游戏,但是,如果我不能在一行上做一件事,代码可能会很快失控。

首先,源代码:

from sys import exit

prompt = "> "
inventory = []

def menu():
    while True:
        print "Enter \"start game\" to start playing."
        print "Enter \"password\" to skip to the level you want."
        print "Enter \"exit\" to exit the game."
        choice = raw_input(prompt)
        if choice == "start game":
            shell()
        elif choice == "password":
            password()
        elif choice == "exit":
            exit(0)
        else:
            print "Input invalid. Try again."

def password():
    print "Enter a password."
    password = raw_input(prompt)
    if password == "go back":
        print "Going to menu..."
    else:
        print "Wrong password. You are trying to cheat by (pointlessly) guess passwords."
        dead("cheating")

def shell(location="default", item ="nothing"):
    if location == "default" and item == "nothing":
        print "Starting game..."
        # starter_room (disabled until room is actually made)
    elif location != "default" and item != "nothing":
        print "You picked up %s." % item
        inventory.append(item)
        location()
    elif location != "default" and item == "nothing":
        print "You enter the room."
        location()
    else:
        print "Error: Closing game."

def location():
    print "Nothing to see here."
    # Placeholder location so the script won't spout errors.

def dead(reason):
    print "You died of %s." % reason
    exit(0)

print "Welcome."
menu()

首先,解释我的游戏基本上如何运作。 游戏中有一个“贝壳”。 (输入完成的地方)从不同的房间接收信息并将信息发送到不同的房间。在游戏中,它存储库存。它可以接收两个参数,即位置和要添加到库存的最终项目。然而,第40-42行(第一个elif块在' shell')和第43-45行(最后一个elif块在' shell')应该回到任何位置位置是(第42和45行,确切地说)。我已尝试过"%s()%location"但这并不起作用,它似乎只在打印东西时起作用。

有没有办法做到这一点?如果没有,即使为这个游戏编写引擎也是一场噩梦。或者我必须制作一个完全不同的引擎,在这种情况下我认为这是一种更好的方法。

对不起,如果我犯了任何错误,请先提问/张贴。

3 个答案:

答案 0 :(得分:1)

elif location != "default" and item != "nothing":
    print "You picked up %s." % item
    inventory.append(item)
    location()
elif location != "default" and item == "nothing":
    print "You enter the room."
    location()

我想你想调用一个名字的函数。为此,您需要对其中定义的模块或类的引用:

module = some_module # where the function is defined
function = getattr(module, location) # get the reference to the function
function() # call the function

如果在当前模块中定义了该功能:

function = globals()[location]
function() # call the function

答案 1 :(得分:0)

如果我正确理解你想要的是这样的东西:玩家将输入一个位置名称,你想调用相关的方法。 "%s"()%location将不起作用,一个字符串(即“%s”不可调用)。

让我们试试OOP方式:

class Maze:
   def __init__(self):
      # do what you need to initialize your maze

   def bathroom(self):
      #go to the bathroom

   def kitchen(self):
      # go to the kitchen

   def shell(self, location="", item=""):
      if location == "" and item == "":
         print "Starting game..."
         # starter_room (disabled until room is actually made)
      elif location and item:
         print "You picked up %s." % item
         inventory.append(item)
         getattr(self, location)()
      elif location and item == "":
         print "You enter the room."
         getattr(self, location)()
      else:
         print "Error: Closing game."

maze = Maze()
while True:   # or whatever you want as stop condition
   location = raw_input("enter your location :")
   item = raw_input("enter your location :")
   maze.shell(location=location, item=item)

答案 2 :(得分:0)

我认为你可以使用getattr()方法。

示例:您想从模块“test”调用方法“helloword()”,然后执行:

methodYouWantToCall = getattr(test, "helloworld")
caller = methodYouWantToCall()

希望它能为您提供线索。