基于文本的冒险游戏,攻击会使游戏崩溃

时间:2019-08-18 15:32:57

标签: python python-3.x

我已经为玩家设置了攻击敌人的功能,这似乎还可以。问题是攻击的实际行动。在我的主要游戏代码中,它抛出AttributeError。

这是我认为是罪魁祸首的代码块(至少,这是错误所引用的代码块):

def choose_action(room, player):
    action = None
    while not action:
        available_actions = get_available_actions(room, player)
        action_input = input("Action: ")
        action = available_actions.get(action_input)
        if action:
            action()
        else:
            print("Invalid selection!")

游戏运行得很好,直到我们遇到一个敌人,然后我们去攻击它。键入攻击热键后,游戏将崩溃并显示以下错误:

game.py", line 53, in choose_action
    action = available_actions.get(action_input)
AttributeError: 'NoneType' object has no attribute 'get'

我一般对编程都不熟悉,我正在用一本书来帮助我创建这个游戏。我已经完全按照书中的代码复制了代码,所以我只是想找出我需要更改的内容,以使攻击操作正常进行。

编辑:根据要求,这是get_available_actions()函数:

def get_available_actions(room, player):
    actions = OrderedDict()
    print("Choose an action: ")
    if player.inventory:
        action_adder(actions, 'i', player.print_inventory, "Print inventory")
    if isinstance(room, world.EnemyTile) and room.enemy.is_alive():
        action_adder(actions, 'a', player.attack, "Attack")
    else:
        if world.tile_at(room.x, room.y - 1):
            action_adder(actions, 'n', player.move_north, "Go north")
        if world.tile_at(room.x, room.y + 1):
            action_adder(actions, 's', player.move_south, "Go south")
        if world.tile_at(room.x + 1, room.y):
            action_adder(actions, 'e', player.move_east, "Go east")
        if world.tile_at(room.x - 1, room.y):
            action_adder(actions, 'w', player.move_west, "Go west")
        if player.hp < 100:
            action_adder(actions, 'h', player.heal, "Heal")

        return actions

1 个答案:

答案 0 :(得分:2)

最好添加get_available_actions(arg1, arg2)函数。看来此函数没有返回值或没有返回值(与此相同)。

如果您可以添加更多代码,我们可以进一步分析此错误。否则,您应该尝试使用方法.get(arg1, arg2)将返回值更改为某些值。

希望这会有所帮助!

使用您编辑中的新信息...看来您的return语句打算缩进少一个标签,请检查以下代码并进行此更改,看看这是否可以解决您的问题:

def get_available_actions(room, player):
    actions = OrderedDict()
    print("Choose an action: ")
    if player.inventory:
        action_adder(actions, 'i', player.print_inventory, "Print inventory")
    if isinstance(room, world.EnemyTile) and room.enemy.is_alive():
        action_adder(actions, 'a', player.attack, "Attack")
    else:
        if world.tile_at(room.x, room.y - 1):
            action_adder(actions, 'n', player.move_north, "Go north")
        if world.tile_at(room.x, room.y + 1):
            action_adder(actions, 's', player.move_south, "Go south")
        if world.tile_at(room.x + 1, room.y):
            action_adder(actions, 'e', player.move_east, "Go east")
        if world.tile_at(room.x - 1, room.y):
            action_adder(actions, 'w', player.move_west, "Go west")
        if player.hp < 100:
            action_adder(actions, 'h', player.heal, "Heal")

    return actions

祝你好运!

相关问题