簡體   English   中英

Python 基於文本的游戲中的類型錯誤

[英]TypeError in Python Text Based Game

我正在為 class 開發基於文本的游戲。我已經編寫了其中的大部分內容,但是當我 go 對其進行測試時,我遇到了 TypeError: unhasable type: 'list' 錯誤。

def show_instructions():
    # Defines what the instructions so they are easily recalled later
    print('x' * 75)
    print('Escape from the Magic Prison!')
    print('Collect six talismans from the different rooms in the prison.')
    print('Avoid the Warden at all cost!')
    print('If there is an item in the room you are in say: "Get [Item Name]"')
    print('Move to different rooms by saying: "Go [Direction]"')
    print('x' * 75)
    # Print x * 75 to break up the lines so it looks better


def player_status(inventory, current_room, rooms):
    # Defines player_status to easily recall this below
    print('x' * 75)
    print('You are currently in', current_room)
    print('Current Inventory:', inventory)
    if 'item' in rooms[current_room]:
        print('There is a', rooms[current_room]['item'], 'on the floor.')
    print('x' * 75)


def game():
    inventory = []
    # Sets user to start with no inventory
    rooms = {
        'Jail Cell': {'South': 'Shower Room'},
        'Shower Room': {'North': 'Jail Cell', 'East': 'Mess Hall', 'item': 'Razor Talisman'},
        'Mess Hall': {'West': 'Shower Room', 'North': 'Kitchen', 'East': 'Commissary', 'South': 'Yard',
                      'item': 'Spoon Talisman'},
        'Yard': {'North': 'Mess Hall', 'item': 'Wire Cutter Talisman'},
        'Kitchen': {'South': 'Mess Hall', 'item': 'Ladle Talisman'},
        'Commissary': {'West': 'Mess Hall', 'North': "Warden's Office", 'East': 'Library', 'item': 'Token Talisman'},
        "Warden's Office": {'South': 'Commissary', 'item': 'Warden'},
        'Library': {'West': 'Commissary', 'item': 'Date Stamp Talisman'}
    }
    # Defines the rooms, which directions you can go from while in that room, and what item the room amy have.
    current_room = ['Jail Cell']
    # Sets the users starting room.

    show_instructions()

    while True:

        player_status(inventory, current_room, rooms)
        command = input('What would you like to do? \n')

        if len(inventory) == 6:
            print('You got all of the required talisman!')
            print('You are now able to walk through walls after obtaining all of the talismans!')
            print('You leave the prison using your new ability.')
            print('x' * 75)
            print('Game over, you won!')
            print('x' * 75)
        elif command.split()[0].capitalize() == 'GO':
            command = command.split()[1].capitalize()
            if command in rooms[current_room]:
                current_room = rooms[current_room][command]
                if current_room == "Warden's Office":
                    print("You have entered the Warden's Office! \n The warden binds you with their magic."
                          "\n The warden locks you back into your jail cell.")
                    print('x' * 75)
                    print('Game Over \n Thanks for playing.')
                    print('x' * 75)
                    break
            else:
                print('There is no door that way.')
        elif command.split()[0].capitalize() == 'GET':
            command = command.split()[1].capitalize()
            if command in rooms[current_room]['item']:
                inventory.append(command)
                del rooms[current_room]['item']
            else:
                print('Invalid input, check spelling.')
        else:
            print('Invalid input, check spelling.')

game()

這是我正在運行的代碼,這是我得到的確切錯誤:

Traceback (most recent call last):
  File "C:\Users\tyler\PycharmProjects\VariousSchool\TextBasedGame.py", line 84, in <module>
    game()
  File "C:\Users\tyler\PycharmProjects\VariousSchool\TextBasedGame.py", line 50, in game
    player_status(inventory, current_room, rooms)
  File "C:\Users\tyler\PycharmProjects\VariousSchool\TextBasedGame.py", line 22, in player_status
    if 'item' in rooms[current_room]:
                 ~~~~~^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'

我不確定還能嘗試什么,我查看了變量和我擁有的所有內容,但它一直回到這個錯誤。

Python 中的可變類型不可哈希,因為等式的行為可能會隨着元素的變化而改變,這應該會改變 hash(這是不可能的)。 由於集合和字典依賴於散列鍵,不可散列的元素不能是字典的鍵和集合的元素。

可哈希列表的一個很好的替代方法是不可變列表,也稱為元組。 嘗試rooms[tuple(current_room)]


盡管這應該可行,但您的代碼很可疑,因為 current_room 似乎是 singleton。也許您的意思是current_room = 'jail Cell'

據我所知,在第 22 行,您試圖獲取當前房間的可用命令,當前房間存儲在名為current_room的變量中。 但是, current_room是一個列表,括號中的部分需要是可哈希的。 我認為您應該將rooms[current_room]更改為rooms[current_room[0]]以獲取列表中的實際當前房間。 雖然轉換為其他可迭代對象(例如元組)使它們可哈希,但使用它們可能會導致 KeyError,因為rooms字典的鍵是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM