做一个不完整的IF政治家

2024-05-29 09:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个小地牢爬虫文本游戏,有一个特定的代码,我想使用,但我不知道如何。我想创建一个IF语句,它有一个不完整的end语句。你知道吗

if cmd.lower() == "examine ...":

这三个点将是用户选择的任何东西。选项的数量太多了,不可能每个选项都有那么多IF语句。有没有什么方法可以让我把他们输入的“检查”部分用在IF语句中?你知道吗


Tags: 代码用户文本cmd游戏if选项语句
1条回答
网友
1楼 · 发布于 2024-05-29 09:41:03

您需要“标记化”您的输入字符串,然后根据命令“分派”结果,即第一个标记。你知道吗

您可以探索这样的解决方案:

def examine(thing):
    print(f'It is a {thing}')

def attack(target):
    print(f'You strike {target}.  It seems offended.')

def tokenise_input(inp):
    command, *args = inp.split(' ')

    return (command, args)

def dispatch(command, *args):
    commands = {
        'examine': examine,
        'kill': attack,
        'attack': attack,
        ...,
    }

    return commands[command](*args)

command, args = tokenise_input(cmd)

dispatch(command, *args)

我相信您可以想象扩展commands字典以允许用户使用更多命令,每个命令都指向自己的函数。你知道吗

上面的字符串插值语法f'...'是3.6中的新语法,在早期版本中会导致语法错误。我建议您使用3.6,因为它非常棒,但如果您不能使用,请替换如下用法:

def examine(thing):
    print('It is a {thing}'.format(thing=thing))

相关问题 更多 >

    热门问题