2012-09-26 131 views
0

我已经使用字典来允许用户输入内容,但下一个问题是使用第二个字作为被调用函数的参数。目前,我有:使用输入作为字典调用的函数的参数

def moveSouth(): 
    Player.makeMove("south") 
def moveNorth(): 
    Player.makeMove("north") 
def moveEast(): 
    Player.makeMove("east") 
def moveWest(): 
    Player.makeMove("west") 

function_dict = {'move south':moveSouth, 'wait':wait, 'sleep':sleep, 
       'move north':moveNorth, 'move':move, 'look':look, 
       'move east':moveEast, 
       'move west':moveWest} 

而要获得输入:

command = input("> ") 
command = command.lower() 
try: 
    function_dict[command]() 
except KeyError: 
    i = random.randint(0,3) 
    print(responses[i]) 

然而,而不是必须有4个不同的功能,使一招,我希望会有办法以便当用户输入“向南移动”时,它使用第一个字调用该功能,然后使用“南”作为该功能中方向的参数。

+0

为什么你定义'moveWest'和其他呢? –

回答

1

split()输入然后分别通过每个部分。

command = input("> ") 
user_input = command.lower().split() 
command = user_input[0] 
if len(user_input) > 1: 
    parameter = user_input[1] 
    function_dict[command](parameter) 
else: 
    function_dict[command]() 
+0

'睡眠失败' –

+0

@PierreGM今天早上我的感受。添加了一张支票。 – deadly

+0

我知道这种感觉... –

1

如何:

command = input("> ") 
command_parts = command.lower().split(" ") 
try: 
    if len(command_parts) == 2 and command_parts[0] == "move": 
     Player.makeMove(command_parts[1]) 
    else: 
     function_dict[command_parts[0]]() 
except KeyError: 
    i = random.randint(0,3) 
    print(responses[i]) 

基本上我只是尝试用空格分割的输入和由第一部分(移动等待决定命令的类型。 ..)。第二部分用作参数。

0

对于这种类型的命令行处理,您可以轻松使用cmd模块。它允许您通过创建类似do_<cmd>的方法来创建命令,其余行作为参数。

如果你不能使用cmd模块,你将不得不自己解析命令行。你可以使用command.split()来做到这一点。