基于Python

时间:2016-05-06 18:37:57

标签: python python-2.7

我正在尝试在“学习Python艰难的方式”中进行练习36(花一周时间制作基于文本的游戏)。

想要我想要的是运行func_1(x),然后运行func_x(0)。我无法弄清楚如何做到这一点。我尝试过编写func_x(0),但会返回NameError: Global name 'func_' is not defined。我也尝试了func + x + (0),我得到了相同的NameError。我想也许如果我可以在调用它之前将函数的名称放在一起,这样就可以了,所以我做了func = 'func_' + str(x) + '(0)'然后尝试了room但是根本没有做任何事情。当我print时,它确实返回func_x(0)

这是我的代码,我试图让上述内容工作。n, x, o, y包含在内,以便完整。我删除了剩下的代码,使其更加简洁,并在发布之前对其进行了测试,以确保其他所有内容仍然正常运行。

import sys
from time import sleep

def in_room(r, n, x, o, y):

    in_room = True
    search_times = 0
    while in_room == True:
        action = raw_input("What would you like to do?:> ")

        if action == 'search' and search_times < 1:
            print (n, x, o, y)
            search_times += 1
        elif action == 'search' and 1 <= search_times:
            print "There is nothing in the room."
        elif action == 'go through right door':
            in_room = False
        elif action == 'go through left door':
            in_room = False
        elif action == 'look around':
            room_r(0)

def room_1(state):
    words ="""
    You are in a dank room. 
    The walls are wet and the floor slimey.
    There is a door to your left and right.
    The door behind you closes.
    """
    for char in words:
        sleep(0.02)
        sys.stdout.write(char)
        sys.stdout.flush()
    if state == 0:
        return


    in_room(1, 1, 6, 1, 6)

room_1(1)

2 个答案:

答案 0 :(得分:2)

我会使用list来获取您要调用的函数:

funcs = [
    func_0,
    func_1,
    func_2,
]

# Get the correct function
# x would need to be a number 0-2 in this case
func = funcs[x]

# Call the function
func(0)

答案 1 :(得分:0)

您可以通过globals()和locals()查看函数名称,如下所示:

elif action == 'look around':
  fname = "room_%d" % r
  possibles = globals().copy()
  possibles.update(locals())
  func = possibles.get(fname)
  if not func:
       raise NotImplementedError("Function %s not implemented" % fname)
  func(0)