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

m4pnthwp  于 2023-04-20  发布在  PyCharm
关注(0)|答案(1)|浏览(158)

我不知道我做错了什么,(就编码而言,我还是一个初学者),但是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
9njqaruj

9njqaruj1#

要从列表或字典中弹出某些内容,请使用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的初学者教程
希望能有帮助:-)

相关问题