Python 3 如何在将物品添加到库存后从房间中移除物品?

问题描述 投票:0回答:1

我不确定我做错了什么(就编码而言仍然是一个初学者),但是

del rooms[currm]['Item']
行实际上并没有删除该项目。我遵循了其中大部分内容的指南,但我使用的指南并没有删除项目。所以任何帮助将不胜感激。使用 Python 3.

 item & direction declaration
item = None
direction = 'direction'


def instructions():
    # print main menu and the commands
    print('\n' + ('\t' * 18) + f'''Evil Sorceress Text Adventure Game\n
                  Collect all 6 items to win the game, or be destroyed by the Evil Sorceress, Daeris.
                  Move commands: 'Go {direction}' (North, South, East, West)
                  Add to Inventory: Get {'Item'}\n\n''')


def prologue():  # story set up
    print('\t\tThe Evil Sorceress, Thalya, has taken over the castle of a neighboring kingdom for her Master:')
    print('\n' + ('\t' * 10) + '\033[1m' + 'The Ultimate Evil.' + '\033[0m\n')
    print('''\t\tIt’s up to you to defeat her and reclaim it for the forces of Good! You’ll enter via the Gatehouse.
        You must Get some Armor from the Guard Room for melee protection.
        An Amulet for magical protection from the Enchanting Room.
        A Spellbook from the Library to take down her magical shield.
        A Torch from the Courtyard to light the room.
        A Sword from the Armory to defeat her.
        And finally a Turkey Leg from the Great Hall because fighting evil on an empty stomach is never a good idea!'''
          '\n')


# room, item and direction assignments
rooms = {'Throne Room': {'South': 'Great Hall', 'Boss': 'Daeris'},
         'Great Hall': {'North': 'Throne Room', 'West': 'Library', 'South': 'Courtyard', 'East': 'Armory',
                        'Item': 'Turkey Leg'},
         'Library': {'East': 'Great Hall', 'Item': 'Spellbook'},
         'Courtyard': {'North': 'Great Hall', 'South': 'Gatehouse', 'East': 'Enchanting Room', 'Item': 'Torch'},
         'Armory': {'West': 'Great Hall', 'South': 'Enchanting Room', 'Item': 'Sword'},
         'Enchanting Room': {'North': 'Armory', 'West': 'Courtyard', 'Item': 'Amulet'},
         'Gatehouse': {'North': 'Courtyard', 'East': 'Guard House', },
         'Guard House': {'West': 'Gatehouse', 'Item': 'Armor'},
         }

inv = []  # assigns inventory variable
vowels = ['a', 'e', 'i', 'o', 'u']  # List of vowels
currm = 'Gatehouse'  # Assigns starting room as the Gatehouse
pin = ''  # Returns results of previous input

# prints prologue & instructions
prologue()
input('\n Press any key to continue\n\n')
instructions()

# gameplay loop
while True:
    print(f'\nCurrent Position: {currm}\nInventory : {inv}\n{"~" * 27}')
    print(pin)

    #  Item pickup prompt
    if 'Item' in rooms[currm].keys():
        nitem = rooms[currm]['Item']
        if nitem not in inv:
            if nitem[0] not in vowels:
                print(f"There's an {nitem} here. Take it?\n")
            else:
                print(f"There's a {nitem} here. Take it?\n")

    if 'Boss' in rooms[currm].keys():  # Game End parameters
        if len(inv) == 6:
            print('''Congratulations!
            You've reached the Throne Room and defeated the Evil Sorceress, Daeris.
            And have therefore reclaimed the castle for the forces of Good!!''')
            break
        else:
            print('Daeris has defeated you and The Ultimate Evil is victorious!')
            break

    # Accepts player's move as input
    uin = input('Enter your move:\n')

    # Splits move into words
    move = uin.split(' ')

    # First word is the action
    action = move[0].title()

    # Second word is object or direction
    if len(move) > 1:
        item = move[1:]
        direction = move[1].title()
        item = ' '.join(item).title()

        # Moving between rooms
    if action == 'Go':
        try:
            currm = rooms[currm][direction]
            pin = f'You head {direction}\n'
        except:
            pin = 'INVALID DIRECTION!\n'

            # Picking up items
    elif action == 'Get':
        try:
            if item == rooms[currm]['Item']:
                if item not in inv:
                    inv.append(rooms[currm]['Item'])
                    if item == ['Turkey Leg']:
                        pin = f'{item} obtained! Om nom nom.\n'
                    else:
                        pin = f'{item} obtained!\n'
                else:
                    del rooms[currm]['Item']  # deletes item if already obtained
            else:
                print('No item here')
        except:
            pin = f'That {item} is located elsewhere'

最初拿起物品结果是:

Enter your move:
get armor

Current Position: Guard House
Inventory : ['Armor']
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Armor obtained!

但是,如果我尝试再次拿起该物品,它就像我一开始就没有拿起它一样,并返回相同的结果。我不是 100% 相信会发生什么,但基本上这就是我想要的结果。

Enter your move:
get armor

No item here

我尝试将其移回以符合

if item == rooms[currm]['Item']:
以查看是否是问题所在,但这也没有用。

else:
                    del rooms[currm]['Item']  # deletes item if already obtained
python python-3.x pycharm
1个回答
0
投票

要从列表或字典中弹出某些内容,请使用

pop()
,而不是
del

test_dict = {
    "hello": 2,
    "this": 3,
    "is": 5,
    "an": 5,
    "example": 28,
}

new = test_dict.pop("hello")

print(new)
print(test_dict)
2
{'this': 3, 'is': 5, 'an': 5, 'example': 28}

del
做了一些完全不同的事情:它从当前范围的“内存”(这很复杂)中删除了一些东西。除非你正在用这门语言做一些真正高级的事情(而且你不会在第一年使用它),否则你不需要
del
,也不需要理解它的作用。通常会有更清洁的方法。
pop
在这种情况下就是这样。

老实说,最好阅读一些关于 listsdicts

的初学者教程

希望对您有所帮助。 :-)

© www.soinside.com 2019 - 2024. All rights reserved.