【问题标题】:list index out of range.split on input?列表索引超出范围。输入时拆分?
【发布时间】:2017-10-24 08:46:28
【问题描述】:

我在输入和输入单个单词时遇到了“超出范围”。我理解为什么它们超出范围,我只是找不到解决问题的方法。这是我的代码:

commands = {
'help': help,
'exit': exit,
'look': look,
'stats': thePlayer.printStats,
's':thePlayer.move_South}

def runCmd(cmd, args, player):
    commands[cmd](args, player)

def help(args):
    print(commands)

def play():
    main1()
    World.loadTiles()
    #These lines load the starting room and display the text
    room = World.tileExists(player.locationX, player.locationY)
    print(room.introText())
    while player.isAlive():
        room = World.tileExists(player.locationX, player.locationY)
        room.modifyPlayer(player)
        # Check again since the room could have changed the player's state
        if player.isAlive():
            print("\nHp:%d\%d  Mp:%d\%d\n"%(player.hp,player.maxHp,player.mp,player.maxMp))
            print(room.printEnemy())
            availableActions = room.availableActions()            
            for action in availableActions:
                print(action)
            actionInput = input('Action: ')
            action = actionInput.lower()
            action = action.split()            
            print(action)
        if action[0] in commands:
            runCmd(action[0],action[1], player)

我意识到我没有传递“动作 [1]”,并且只是按 Enter 键不在“命令”中导致我的错误。我是编码新手,所以创建游戏是我自学的方式。

我正试图到达我可以输入的位置:输入、单字(帮助、统计)、双字(看老鼠)、其他有更多单词的东西(购买大剑)等等。关于如何正确编码的任何帮助?

【问题讨论】:

    标签: python-3.x text-based


    【解决方案1】:

    测试怎么样

    len(action)
    

    在调用 runCmd 之前?因此,您可以知道是否有一个词、两个词或两个以上的词。 如果只有一个词,可以调用:

    runCmd(action[0], None, player)
    

    如果有两个词,你可以调用你当前的函数。如果有两个以上的单词,那就有点棘手了。您可以传递整个动作变量。然后,被调用的函数必须知道它需要多少个参数。

    【讨论】:

    • 这将是一种非常暴力的方法来使其工作。但是,这将增加 20 次额外的代码,我确信可以简化这些代码。我知道有一个 *args 我可以通过,而不是(据我所知)它将作为我想要的参数传递,但是我还不知道如何准确地使用它。
    • 我没用过 splat 运算符,所以帮不了你。或许你能找到一些线索here。它是 Python 2,但我认为它也适用于 Python 3。
    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多