[英]Using user input to call functions
I was trying to make a "game" in Python where the user inputs a command. 我试图用Python在用户输入命令的地方做一个“游戏”。 However, I do not know whether you can take that input to be a function name. 但是,我不知道您是否可以将该输入用作函数名。 This is my current effort: 这是我目前的努力:
def move():
print("Test.")
if __name__ == "__main__":
input("Press enter to begin.")
currentEnvironment = getNewEnvironment(environments)
currentTimeOfDay = getTime(timeTicks, timeOfDay)
print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
command = input("> ")
command()
Here, the input was move, as I wanted to try and call that function (as a potential end user might). 在这里,输入是移动的,就像我想尝试调用该函数一样(潜在的最终用户可能会这样)。 However, I get the following error: 但是,出现以下错误:
Traceback (most recent call last):
File "D:\Text Adventure.py", line 64, in <module>
command()
TypeError: 'str' object is not callable
I was wondering if there was any way that I could allow a user to 'move' in the game, which the program achieves by calling the "move" function. 我想知道是否有什么方法可以允许用户在游戏中“移动”,程序通过调用“移动”功能来实现。
It looks like you're using python3.x where input
returns a string. 看起来您正在使用python3.x,其中input
返回一个字符串。 To recover the python2.x behavior, you need eval(input())
. 要恢复python2.x的行为,您需要eval(input())
。 However, you shouldn't do this. 但是,您不应该这样做。 It's likely to lead to a bad day. 可能会导致糟糕的一天。
A better idea is to put the functions into a dictionary -- 一个更好的主意是将函数放入字典中-
def move():
#...
def jump():
#...
function_dict = {'move':move, 'jump':jump }
and then: 接着:
func = input('>') #raw_input on python2.x
function_dict[func]()
The following code works for me on python3.2. 以下代码在python3.2上对我有用。
def move():
print("Test.")
func_dict = {'move':move}
if __name__ == "__main__":
input("Press enter to begin.")
currentEnvironment = "room" #getNewEnvironment(environments)
currentTimeOfDay = "1 A.M." #getTime(timeTicks, timeOfDay)
print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
command = input("> ")
func_dict[command]()
Have a look at the cmd
module. 看看cmd
模块。 See this . 看到这个 。
It is normally used for shell style comman dlanguages, but it can also be used to create simple text style adventure games. 它通常用于外壳样式的命令语言,但也可以用于创建简单的文本样式的冒险游戏。
You can create commands by creating a new method on the Cmd
subclass. 您可以通过在Cmd
子类上创建新方法来创建命令。
Eg 例如
def do_move(self, args):
if self.next_room.has_snake():
print "The next room contains a poisonous snake. It bites you and you die."
else:
print "The room is empty"
You can access functions by name using: 您可以使用以下名称来访问功能:
function = globals()[function_name]
if the function is in the current module, or 如果功能在当前模块中,或者
function = getattr(other_module, function_name)
You should also take measures to disallow calling arbitrary functions, for example, prefixing: 您还应该采取措施禁止调用任意函数,例如,前缀:
def cmd_move() # ok to call this
def cmd_jump() # ok to call this
def internal_func....
cmd = raw_input('>') # e.g. "move"
fun = globals()['cmd_' + cmd]
fun()
按照Hans的建议,通常最好重用代码,但是如果您想输入命令并手动运行它们,那么拥有有效命令字典比直接执行用户提供的输入要安全得多。
cmd = { 'move': move, 'jump': jump, 'look': look }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.