python-3.x 我在输入无效命令时收到错误,尽管我有一个else语句可以解释它[已关闭]

y53ybaqx  于 2023-02-17  发布在  Python
关注(0)|答案(3)|浏览(97)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
3天前关闭。
Improve this question
我有代码来添加一个项目到库存和删除该项目从口述。它不能正常工作虽然。我有:

# functions to be called later in the code.
def instructions():
    directions = 'North, East, South, West'
    print('\n-------------------------------------------------')
    print(f'Enter a direction: go {directions} or')
    print('equip item: get \'item name\'')
    print('To exit, type \'quit\'.')
    print('-------------------------------------------------')

def player_status(rooms, current_room, inventory):
    print(f'\nYou are at {current_room}.')
    if 'item' in rooms[current_room]:
        print('There is a ' + rooms[current_room]['item'])
    else:
        print('There are no items here.')
    print('You have:', inventory)

# main game loop.
def main():
    inventory = []
    sorted_inv = sorted(inventory)

# a dictionary of rooms and items.
    rooms = {
        'your apartment': {'west': 'occult bookstore', 'south': 'McDally\'s Pub'},

        'occult bookstore': {'east': 'your apartment', 'item': 'skull'},

        'McDally\'s Pub': {'north': 'your apartment', 'east': 'Shedd Aquarium', 'south': 'Wrigley Field',
                           'item': 'energy potion'},

        'Wrigley Field': {'north': 'McDally\'s Pub', 'west': 'your office', 'item': "wizard\'s staff"},

        'your office': {'east': 'Wrigley Field', 'item': 'Faerie Queen'},

        'Shedd Aquarium': {'west': 'McDally\'s Pub', 'north': 'Field Museum of Natural History',
                           'item': 'enchanted duster'},

        'Field Museum of Natural History': {'south': 'Shedd Aquarium', 'north': 'Saint Mary of the Angels church',
                                            'item': 'blasting rod'},

        'Saint Mary of the Angels church': {'south': 'Field Museum of Natural History', 'item': 'shield bracelet'}
    }

# set the start room
    current_room = 'your apartment'

    while True:
# this set of if, elif statements establish win conditions. Still incomplete.
        if sorted_inv == ['blasting rod', 'enchanted duster', 'energy potion', 'shield bracelet', 'skull',
                          "wizard\'s staff"]:
            print('You\'ve got your stuff back. Time to see the Queen.')
        elif current_room == 'your office' and inventory != ['blasting rod', 'enchanted duster', 'energy potion',
                                                             'shield bracelet', 'skull', "wizard\'s staff"]:
            print('You were unprepared. The Queen tears you head off. Game over.')
            break
        elif current_room == 'your office' and sorted_inv == ['blasting rod', 'enchanted duster', 'energy potion',
                                                              'shield bracelet', 'skull', "wizard\'s staff"]:
            print('The Faerie Queen has terrorized your city for the last time.')
            break

        instructions()
        player_status(rooms, current_room, inventory)
        time.sleep(0.5)

        # sets up user command to move player between rooms.
        command = input('\nWhat do you want to do?\n> ').lower().strip()

        # if command is empty.
        if command.strip() == '':
            print('\nPlease enter a command.')
            time.sleep(0.5)

        elif command.lower().split()[0] == 'go':
            direction = command.lower().split(' ')[1]
            if direction in rooms[current_room]:
                current_room = rooms[current_room][direction]
                time.sleep(0.5)

            # if player inputs an invalid command.
            else:
                print('\nYou can\'t go that way!')
                time.sleep(1)

        # command to add item to inventory and remove it from dict.
        elif command.lower().split()[0] == 'get':
            obj = command.lower().split(maxsplit=1)[1]

            if obj not in rooms[current_room]['item']:
                print('you don\'t see that here.')
                time.sleep(1)

            elif obj in rooms[current_room]['item']:
                # current_room = rooms[current_room][obj]
                del rooms[current_room]['item']
                inventory.append(obj)
                time.sleep(0.5)

            # if player inputs an invalid command.
            else:
                print('\nYou don\'t see that here.')
                time.sleep(1)

        # a command to quit the game.
        elif command.lower() in ('q', 'quit'):
            time.sleep(0.5)
            print('\nThanks for playing.')
            break

        else:
            print('\nPlease enter a valid command.')
            time.sleep(1)

if __name__ == "__main__":
    main()

我希望,如果玩家犯了一个错误,并试图添加一个物品到库存,他们已经有或不是一个项目在该房间(或打字错误),代码将输出'You don 't see that here.'而不是崩溃。@上帝是一个:rooms是一个字典,其余代码引用它来进行移动和项目。@ Galo do Leste:我想我是在尝试考虑所有可能的输入,但逻辑上,除了is True和is False之外,不应该有其他输入。

czq61nw1

czq61nw11#

找到解决办法了。只要把一切都想好...

if obj in inventory:
    print('\nYou\'ve already picked that up.')
    time.sleep(1)

这将检查该项目是否已经放入库存。用以下代码替换if obj not in语句。

g0czyy6m

g0czyy6m2#

这可能与您的房间[current_room]是如何设置的有关。看起来房间[current_room]是一个基于您的代码的字典,对它执行[“item”]操作可以让它在该字典中查找“item”键。然而,该键在字典中不存在,因此抛出KeyError。而在您提供的错误中,它显示了确实具有该键的房间。它还显示房间没有物品,这是当“物品”不在房间[current_room]中时导致的,意味着物品密钥被移除。
您可能希望在try/catch块中或使用.get首先尝试获取“item(“item”)并检查None,特别是当您在初始化中有没有“item”键的房间时,或者执行类似于您已经执行的操作,检查“item”键是否在room[current_room]字典中。你可以在if块中用你的item键的检查来包围当前的代码。

elif command.lower().split()[0] == 'get':
    if 'item' in rooms[current_room]:
        obj = command.lower().split(maxsplit=1)[1]

        if obj not in rooms[current_room]['item']:
            print('you don\'t see that here.')
            time.sleep(1)

        elif obj in rooms[current_room]['item']:
            # current_room = rooms[current_room][obj]
            del rooms[current_room]['item']
            inventory.append(obj)
            time.sleep(0.5)

        # if player inputs an invalid command.
        else:
            print('\nYou don\'t see that here.')
            time.sleep(1)elif command.lower().split()[0] == 'get':
            
    #room does not have a "item" key
    else:
        print('\nYou don\'t see that here.')
        time.sleep(1)
qgelzfjb

qgelzfjb3#

# command to add item to inventory and remove it from dict.
elif command.lower().split()[0] == 'get':
    obj = command.lower().split(maxsplit=1)[1]

    if obj not in rooms[current_room]['item']:
        print('you don\'t see that here.')
        time.sleep(1)

    elif obj in rooms[current_room]['item']:
        # current_room = rooms[current_room][obj]
        del rooms[current_room]['item']
        inventory.append(obj)
        time.sleep(0.5)

当玩家拿起一个物品时,代码调用del,它将从房间字典中完全删除“item”键。
但是如果玩家试图在同一个房间里拿起另一件物品,代码仍然会试图访问“物品”键,现在这是一个错误,因为它被移除了。
当玩家拾取一个项目时,最好将rooms[current_room]['item']重新分配给一个空字符串,而不是调用del,这样键仍然存在。

相关问题