简体   繁体   English

在输入中检查部分匹配是否匹配带有不同前缀的有效参数列表

[英]Checking a partial match in input to a list of valid arguments with varying prefixes

So I'm working on a text based game in which I want the user to type their next action in. I'm trying to work out a way to code it so that it may be less "picky". 因此,我正在开发一个基于文本的游戏,在该游戏中,我希望用户键入其下一个动作。我正在尝试找到一种编码方法,以使其不那么“挑剔”。 I want the game to accept partial input (for example n instead of north), also I want it to ignore prefixes such as "go". 我希望游戏接受部分输入(例如,用n代替北),也希望它忽略诸如“ go”之类的前缀。

I've worked out the partial input with a for-loop, it also accepts input with the "go" prefix. 我用for循环算出了部分输入,它也接受带有“ go”前缀的输入。 However, if I simply type "go" without entering a direction it defaults to "north", which is the first part of my list of valid commands. 但是,如果我只是输入“ go”而不输入方向,则默认为“ north”,这是有效命令列表的第一部分。 This problem also appears when giving empty input. 给空输入时也会出现此问题。

What I'm looking for now is a way to let the prefix vary, with something like "check" in front of map or "walk" in front of south. 我现在正在寻找的是一种使前缀有所变化的方法,例如在地图前面使用“ check”或在南部前面使用“ walk”。 I also need to make it recognize when the input only contains a prefix and not an actual command. 当输入仅包含前缀而不是实际命令时,我还需要使其识别。

This is the relevant code at the moment. 这是目前的相关代码。

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

You can try splitting it to words: 您可以尝试将其拆分为单词:

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

If you want to have different prefixes for different commands, you can have something like: 如果要为不同的命令使用不同的前缀,则可以使用以下命令:

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')

But it is starting to look too complex. 但这看起来太复杂了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM