Python 文字游戏:如果 elif 语句不返回上下文相关信息(例如,没有项目描述的房间描述)

Python Text Game: If Elif Statement Doesn't Return Context-Dependent Info (e.g., Room Description without Item Description)

提问人:Skiing Downhill 提问时间:7/25/2023 更新时间:7/25/2023 访问量:37

问:

我创建了一个简单的 Python 文本游戏,它允许玩家从一个房间“移动”到另一个房间,并从每个房间“拿走”物品,将它们添加到玩家库存中。

不过,我正在尝试添加一个基本的增强功能,该增强功能会向玩家返回与上下文相关的房间描述,具体取决于他们是否已经拿走了房间的物品。

例如,当玩家第一次进入房间 2 时,他们将收到一个房间描述和物品描述。

如果他们“拿走”了房间 2 的物品,离开了房间,然后返回,玩家将收到一个没有物品描述的房间描述(因为房间物品已经在他们的库存中)。

这似乎应该是一个非常简单的 If-Elif-Else 语句,但是,使用下面的代码,当玩家返回房间时,在拿走该房间的物品后,我得到一个 KeyError,它记录了房间的名称(例如,“房间 2”)。

当我尝试代码的变体时,我收到的另一个结果是没有项目描述的房间描述,即使在第一次输入时(即,在房间项目被“拿走”之前,返回没有项目描述)。

我对代码中需要更正的内容感到困惑;任何帮助将不胜感激!


class Player(object):
    def __init__(self, current_room):
        self.current_room

inventory = []

Player.current_room = 'room 1'
inventory.append('Key')
new_game = True

def move_player(selected_action):

    # Splits Player input String to determine selected Direction of movement
    split_action = selected_action.split(' ', 1)
    direction = split_action[1]

    # Determines viability of selected Player direction through reference to >> rooms << Dictionary
    if direction in rooms[Player.current_room]:
        Player.current_room = rooms[Player.current_room][direction]

        # current_room_item = room_items[Player.current_room] # Tried to assign Current Room Item to Variable for use in If Statement below

        # THIS IF ELSE DOESN'T WORK FOR SOME REASON, RETURNS KeyError
        # if current_room_item in inventory: # Tried this variation using the variable above, didn't work (KeyError)
        print(room_items[Player.current_room])
        if room_items[Player.current_room] in inventory: # Checks to see if the Item for the Current Room is in Player Inventory
            print(roomONLY_desc[Player.current_room]) # If Room Item IS in Inventory, print Room Only Description
        else:
            print(roomITEM_desc[Player.current_room]) # If Room Item is NOT in Inventory, prints Room Description WITH Item
    else:
        print('There\'s nothing in that direction.')

    # Assigns newly-entered Room to current_room Property of Player Class
    return Player.current_room

def take_item(selected_action):
    # Splits Player input String to determine Item the Player wishes to add to Inventory
    split_action = selected_action.split(' ', 1)
    selected_item = split_action[1]
    print(selected_item)
    print(selected_item == room_items[Player.current_room])

    # Determines if Player-identified Item is a valid Game Item, and if it is located in the Current Room
    if selected_item == room_items[Player.current_room]:
        inventory.append(room_items[Player.current_room])
        print(
            f'''
        You've added the {room_items[Player.current_room]} to your Inventory!

        Your inventory contains: {inventory}

                \u2B50   \u2B50   \u2B50
            '''
        )
        room_items.pop(Player.current_room)
    else:
        print("No such item is available to pick up.")

def main():

    while new_game:

        print(f'In Room: {Player.current_room}')
        selected_action = input('Action: ')
        action = selected_action.split()

        if action[0] == 'move':
            move_player(selected_action)
        elif action[0] == 'take':
            take_item(selected_action)
        elif action[0] == 'exit':
            print('Exit')
            break
        else:
            print('Invalid')

rooms = {
    'room 1': {'E': 'room 2'},
    'room 2': {'E': 'room 3', 'W': 'room 1'},
    'room 3': {'W': 'room 2'}
}

room_items = {
    'room 1': 'item 1',
    'room 2': 'item 2',
    'room 3': 'item 3'}

roomITEM_desc = {
    'room 1': 'room 1 ITEM: item 1',
    'room 2': 'room 2 ITEM: item 2',
    'room 3': 'room 3 ITEM: item 3'
}

roomONLY_desc = {
    'room 1': '1 withOUT item',
    'room 2': '2 withOUT item',
    'room 3': '3 withOUT item'
}

main()

python-3.x if语句

评论

0赞 quamrana 7/25/2023
请使用完整的错误回溯更新您的问题。
1赞 Swifty 7/25/2023
我没有详细阅读您的代码,但是在函数中,您从room_items弹出了项条目,因此难怪您后来会收到密钥错误;最好使用布尔值设置一个字典,并测试此字典以确定要使用的房间描述。take_itemitem_taken

答:

0赞 nrhoopes 7/25/2023 #1

该错误是由弹出 中的键引起的。该行是:因为您不是简单地从字典中的该键中删除该项,而是完全删除整个键。这就是您收到 KeyError 的原因,因为“钥匙”不再存在,因为您在从房间中取出物品后弹出它。然后,一旦你试图重新进入房间,你就在寻找那把钥匙,它不再存在。room_itemsroom_items.pop(Player.current_room)

您可以通过不再弹出项目并执行某些操作来解决此问题,例如将其设置为其他值,例如 .该行将允许您将密钥保留在字典中,但不再与“项目 2”相关联。然而,这意味着您将不得不改变检查物品是否不再在房间中的方式。我建议也许制作一个与项目列表相关的房间字典,而不仅仅是一个字符串,并从列表中删除该项目,而不是从 .room_items[Player.current_room] = ""room_items

它可能看起来像这样:

room_items = {
   'room 1': ['item 1'],
   'room 2': ['item 2', 'item 4'],
   'room 3': ['item 3']
}

这样,您可以在一个房间中拥有多个项目,并验证该项目是否确实在该房间中。

if 'item 2' in room_items['room 2']:
   # The item is in the room
else:
   # The item is not in the room

然后从该列表中删除该项目:room_items['room 2'].remove('item 2')

评论

0赞 Skiing Downhill 7/25/2023
谢谢!我会做出改变,我确实需要修改我对所采取物品的检查,但它解决了这个问题,非常感谢您的帮助