所以快速分析...你让文本解析器其工作过程如下:
- 获取“命令”的第一个字,如果我们不知道这个词的用户使用无效的输入不 - >通知并重新启动
- 如果用户使用已知的“命令”,解析它的参数(如:
go north
,go south
),并让“嵌套”功能拍摄参数的照顾
注意“主解析功能”并不需要知道go()
参数是否有效,进行验证,以go()
它只是代表的责任。
所以我认为你应该建立code (class)这样的:
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
注:我没有测试代码,它只是我的头。
你的意思是“被识别”是什么意思?你的代码中有太多的条件,哪一个被识别? –
由公认的我的意思是如果theres一个单词thats不意味着在那里例如“去”是一个公认的词,但“efwqef”不是。 所以用于例如用户输入 去fwqefuqwe 它会说对不起,我不能那样做 – user2232076