0

所以我正在开发一个基于文本的游戏,我希望用户在其中输入他们的下一个动作。我正在尝试找出一种对其进行编码的方法,以便它可能不那么“挑剔”。我希望游戏接受部分输入(例如 n 而不是北),我也希望它忽略诸如“go”之类的前缀。

我已经用 for 循环计算出部分输入,它也接受带有“go”前缀的输入。但是,如果我只是键入“go”而不输入方向,则默认为“north”,这是我的有效命令列表的第一部分。给出空输入时也会出现此问题。

我现在正在寻找的是一种让前缀变化的方法,例如在地图前使用“检查”或在南前使用“步行”。当输入仅包含前缀而不是实际命令时,我还需要让它识别。

这是目前的相关代码。

move_input = input("You silently ask yourself what to do next.\n").lower()
    for n in valid_moves:
        if n.startswith(move_input) or ("go " + n).startswith(move_input):
            move_input = n
4

1 回答 1

0

您可以尝试将其拆分为单词:

noise = ['go', 'check', 'walk']
commands = [word for word in move_input if word not in noise]
# process commands

如果你想为不同的命令使用不同的前缀,你可以有类似的东西:

prefixes = {('map', 'inventory'): ('check',),
            ('north', 'south', 'east', 'west'): ('go', 'walk')}
commands = [word for word in move_input if word not in noise]
if len(commands) == 1:
   command = commands[0]
else:
    assert len(commands) == 2 # or decide what to do otherwise
    for com, pref in prefixes.items():
        if commands[0] in pref and commands[1] in com:
           command = commands[1]
           break
    else:
        print('Invalid command')

但它开始看起来太复杂了。

于 2013-01-28T17:58:06.793 回答