hey everybody i am building a text based game for a class where i am moving between rooms and trying collect all the items without going into the room with the villian, in this case the Record Executive, and im just having issues accessing the item directly so that I can add it my inventory list..
here is my dictionary:
rooms = {
'Lobby':{'East': 'Bar'},
'Roof':{'South': 'Bar', 'East': 'Stage', 'Item': 'Steel guitar'},
'Bar':{'West': 'Lobby', 'North': 'Roof', 'East': 'Bathroom', 'South': 'Basement', 'Item': 'Keyboard'},
'Basement':{'North': 'Bar', 'East': 'Studio', 'Item': 'Drums'},
'Stage':{'West': 'Roof', 'Item': 'Microphone'},
'Soundcheck':{'South': 'Bathroom', 'Item': 'Bass Guitar'},
'Bathroom':{'North': 'Soundcheck', 'West': 'Bar', 'Item': 'Electric Guitar'},
'Studio': {'West': 'Basement', 'Item': 'Record Executive'}
}
heres my movement code:
while gameOver != True:
playerStats(currentRoom, inventory, rooms)
# currentRoom
playerMove = input('Enter your move:\n')
try:
currentRoom = rooms[currentRoom][playerMove]
except Exception:
print('Invalid move')
continue
I move East from Lobby and my current room changes to Bar like it should but I don't know how to get to the 'Item' property in it so I can add 'Keyboard' to my inventory list... any help would be much appreciated!! thank you
To index the dictionary you want
currentRoom['Item']
You will add it to the list after doing the move, so at the end (after the "try", "except", part) you will add:
inventory.append(currentRoom['Item'])
By putting it after the movement code, you take the item from the new room, not the existing room.
Some rooms might not have an item, so then you can do:
try:
inventory.append(currentRoom['Item'])
except KeyError:
pass
This prevents an error when you move into the room with no item.
Also you might want to remove the item from the room when you take it. So you can do.
try:
inventory.append(currentRoom['Item'])
del currentRoom['Item']
except KeyError:
pass
The del
removes the key from the dictionary
By the way, in your movement code, you should also change
except Exception:
to
except KeyError:
So if there is a different exception (e.g. you press ctrl-C) then it does not catch it.