如此快速的分析......您正在制作文本解析器,其工作方式如下:
- 获取“命令”的第一个单词,如果我们不知道单词用户使用了无效输入 -> 通知并重新启动
- 如果用户使用了已知的“命令”,则解析其参数(如:、、)并让“嵌套”函数处理参数
go north
go south
请注意,“主要解析函数”不需要知道参数go()
是否有效,它只是将验证责任委托给go()
.
所以我认为你应该像这样构建代码(类):
class Game:
# Initialize internal variables, method automatically called on g = Game()
def __init__(self):
self._exit = False
# Array of known commands, used in run, basically maps commands
# to function and it says: if will get 'go' execute self._go
self._commands = {
'go': self._go,
'quit': self._quit
}
# Array of go sub commands, used by _go
self._commands_go = {
'north': self._go_north
# ...
}
# Mathod for parsing command, if it gets "comamnd" returns ("command",None)
# if "command arg1 arg2" returns ("command", "arg1 arg2")
@staticmethod
def parse_command(string):
string = str(string)
index = string.find(' ')
if index < 0:
return (string, None)
return (string[:index], string[index+1:])
# This is main method; the only one which should be called from outside
# It will just read data from input in never ending loop and parse commands
def run(self):
while not self._exit:
src = input('> ')
(command,args) = Game.parse_command( src)
# Do we have this command, execute it
if command in self._commands:
self._commands[command](args)
else:
print( 'I\'m sorry I don\'t known command {}, try one of these:'.format(command))
print( '\n'.join( self._commands.keys()))
#######################################################
# All game commands go here
#######################################################
def _quit(self,args):
self._exit = True
print( 'Bye bye')
# Movement handling, will get executed when user types 'go ...' nad '...' will be in arg
def _go(self,args):
# No argument
if args is None:
print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
return False
# Split sub command anr arguments
(command,args) = Game.parse_command(args)
if command not in self._commands_go:
print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
return False
if args is not None:
print( 'Too many arguments for go')
return False
self._commands_go[command](args)
return True
# Go north
def _go_north(self, args):
print( 'Going north')
game = Game()
game.run()
这将允许您:
- 构建复杂的嵌套命令
- 构建漂亮且可读的命令层次结构(
inventory item 123 update use potion 345
)而不是难读的复杂条件集
- 构建函数别名
go north
可以gn
通过添加'gn': self._go_north
到_commands
- 构建可重用的参数解析
(item_id, action, args) = self._parse_item_action(args)
- 利用面向对象编程的优势(没有全局变量,一切都将是类属性,降低意外变量覆盖的风险)
如果你需要解析goasdf
,go
你可以简单地:
for i in self._commands:
if input.startswirh( i):
return self._commands[i](...)
print('Invalid command')
return False
注意:我没有测试过代码,这只是我的想法。