Items not adding to inventory text based game in python - python

So I have been working on this text based game in python for a project and I have gotten it where I can move around but can not get it where it will pick up the item itself. any help would be greatly appreciated. I am no expert as I am current going to school for programming and still learning.
def game_instructions(): # print a main menu and the commands
print("Killer Clown Text Adventure Game")
print("You must collect all six items to win the game or be killed by the Killer Clown!!")
print("Move commands: go South, go North, go East, go West, Exit")
print("Add to Inventory: get 'item name'")
rooms = {
'Front Gates': {'South': 'Games Area', 'East': 'Ticket Booth', 'item': 'none'},
'Games Area': {'North': 'Front Gates', 'East': 'Prize Area', 'West': 'Food Court', 'South': 'Storage Shed',
'item': 'Big Mallet'},
"Food Court": {'East': 'Games Area', 'item': 'pie'},
'Prize Area': {'West': 'Games Area', 'North': 'Fun House', 'item': 'Net'},
'Fun House': {'South': 'Prize Area', 'item': 'none'},
'Storage Shed': {'North': 'Games Area', 'East': 'Parking Lot', 'item': 'Flash Light'},
'Ticket Booth': {'West': 'Front Gates', 'item': 'Clown-B-Gone Book'},
'Parking Lot': {'West': 'Storage Shed', 'item': 'Keys'}
}
def room_movement(current_room, move, rooms):
current_room = rooms[current_room][move]
return current_room
def user_info():
print('You are in the {}'.format(current_room))
print('Inventory: ', inventory)
print('*' * 25)
def get_item(current_room):
if 'item' in rooms[current_room]: # if statement
return rooms[current_room]['item'] # return statement
else:
return 'This room has no item!' # return statement
game_instructions()
input('Press Enter to Continue')
inventory = []
current_room = 'Front Gates'
move = ''
while current_room != 'Fun House':
user_info()
move = input('Enter your next move.\n').title().split()
item = get_item(current_room)
print('There seems to be an item nearby')
if move == 'take':
move = input('What do you want to take? ').title().split()
if move in rooms[current_room]['item']:
inventory.append(item)
else:
print(f"There's no {item} here.")
if len(move) >= 2 and move[0].lower() == 'go' and move[1].capitalize() in rooms[current_room].keys():
current_room = room_movement(current_room, move[1].capitalize(), rooms)
continue
elif len(move) == 1 and move[0].lower() == 'exit':
current_room = 'exit'
else:
print('Invalid command')

Related

List call and Printing, text-based game

So below is my current code for a text based game that I have to finish for a school project:
# The dictionary links a room to other rooms as well as listing the item in the room
rooms = {
"Crew Quarters": {'East': 'Ship Storage', 'South': 'Operations Deck'},
"Ship Storage": {'West': 'Crew Quarters', 'South': 'Power and Oxygen Control', 'Item': 'Spare O2 Tank'},
"Operations Deck": {'North': 'Crew Quarters', 'East': 'Power and Oxygen Control',
'South': 'Crew Training Chamber', 'West': 'Captain Quarters', 'Item': 'Head Lamp'},
"Power and Oxygen Control": {'North': 'Ship Storage', 'West': 'Operations Deck',
'South': 'Infirmary'},
"Captains Quarters": {'East': 'Operations Deck', 'South': 'Armory', 'Item': 'Key to POC'},
"Armory": {'North': 'Captains Quarters', 'East': 'Crew Training Chamber', 'Item': 'Laser Rifle'},
"Crew Training Chamber": {'North': 'Operations Deck', 'East': 'Infirmary',
'West': 'Armory', 'Item': 'Space Suit'},
"Infirmary": {'North': 'Power and Oxygen Control', 'West': 'Crew Training Chamber', 'Item': 'Med-kit'}
}
# List of commands for movement or to exit the game
directions = ['North', 'South', 'East', 'West']
exit_game = ['e', 'exit']
inv = ['inv']
inv_list = []
# Current / starting room
c_room = 'Crew Quarters'
# print the game name, commands, and objectives.
print("Spaceship Text Adventure")
print("There's been a breach in the Power and Oxygen Control room on the ship!",
"Take care of the threat!")
print("Collect 6 items to defeat the anomaly or let the ship be taken over!")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
print("To check your inventory: 'inv'")
print("To exit the game: 'e' or 'exit'")
# Game Loop
while True:
print('\nYou are in the', c_room)
command = input("\nWhere would you like to go? ")
if command in directions:
if command in rooms[c_room]:
c_room = rooms[c_room][command]
print(c_room)
# 1
else:
print('You cannot go that way')
elif command in inv:
print(inv_list)
elif command in exit_game:
print('You have exited the game. Thank you for playing!')
break
else:
print('Invalid command, try again!')
So what I want/need to do is whenever the player enters a room with an item in it, I need it to display the item that is in that room. If the player already has the item in the inventory, and they go back into the room, i need it to display "You've already taken the item from this room."
Where I placed my #1 is where I feel like the code should go, but I honestly have no idea. Any help would be appreciated as I'm struggling with calling upon lists and printing different statements. TYIA!
In helping out someone else with a similar room navigation game, I had added an inventory list that acquired a copy of the items selected in the various rooms. Following is the sample code.
# data setup
rooms = {'Great Hall': {'name': 'Great Hall', 'item': ['none'], 'south': 'Vendetta Room', 'east': 'Kitchen',
'north': 'Potion Lab', 'west': 'Armory',
'text': 'You are in the Great Hall.'},
'Armory': {'name': 'the Armory', 'item': ['Fire Sword'], 'east': 'Great Hall', 'north': 'Treasure Room',
'text': 'You are in the Armory.'},
'Treasure Room': {'name': 'the Treasure Room', 'item': ['Magic Ring'], 'south': 'Armory',
'text': 'You are in the Treasure Room.'},
'Potion Lab': {'name': 'the Potion Lab', 'item': ['Healing Potion'], 'east': 'Bedroom', 'south': 'Great Hall',
'text': 'You are in the Potion Lab.'},
'Bedroom': {'name': 'the Bedroom', 'item': ['Magic Key'], 'west': 'Potion Lab',
'text': 'You are in the Bedroom.'},
'Kitchen': {'name': 'the Kitchen', 'item': ['Sandwich'], 'south': 'Storage', 'west': 'Great Hall',
'text': 'You are in the Kitchen.'},
'Storage': {'name': 'Storage', 'item': ['Shield'], 'east': 'Mystery Room',
'text': 'You are in Storage.'},
'Mystery Room': {'name': 'The Mystery Room', 'item': ['none'], 'west': 'Storage', 'north': 'Kitchen',
'text': 'You are in the Mystery Room.'},
# villain
'Vendetta Room': {'name': 'the Vendetta Room', 'item': ['none'], 'west': 'Dungeon', 'north': 'Great Hall',
'text': 'You are in the Vendetta Room.'},
# Princess
'Dungeon': {'name': 'the Dungeon', 'item': ['none'], 'east': 'Vendetta Room',
'text': 'You are in the Dungeon.'}
}
directions = ['north', 'south', 'east', 'west']
add_items = ['get item']
current_room = rooms['Great Hall']
inventory = []
def status():
print('-' * 20)
print('You are in the {}'.format(current_room['name']))
print('Your current inventory: {}\n'.format(inventory))
if current_room['item']:
print('Item in room: {}'.format(', '.join(current_room['item'])))
print('')
# game loop
while True:
status()
if current_room['name'] == 'The Mystery Room':
if ['Magic Key'] not in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("You don't have the Magic Key to open the door and end up trapped forever.")
print("GAME OVER")
break
elif ['Magic Key'] in inventory:
print("Oh No! As soon as you entered, the doors locked behind you.")
print("Luckily you found the Magic Key and could unlock the doors to continue your journey.")
if current_room['name'] == 'the Vendetta Room' and len(inventory) > 5:
print("You used all your items to defeat King Nox! Proceed to the next room to save the Princess.")
elif current_room['name'] == 'the Vendetta Room' and len(inventory) < 6:
print("You have found the Demon King but have no weapons.")
print("You have been defeated and the Princess has perished.")
print("GAME OVER")
break
elif current_room['name'] == 'the Dungeon':
print('Congratulations! You have reached the Dungeon and saved the Princess!')
print("You gave the Princess your healing potion and escorted her to the castle.")
print("Thank you for playing!")
break
command = input('Enter Move:')
# movement
if command == 'quit': # Moved this ahead of the directional and acquisition commands
print('Thanks for playing')
break
if command in directions:
if command in current_room:
current_room = rooms[current_room[command]]
elif command != add_items:
# bad movement
print('Invalid entry. Try again.')
# adding inventory
elif command in add_items:
if current_room['item'] != ['none']:
if current_room['item'] in inventory: # No need to acquire an item a second time
print("You already have this item")
else:
inventory.append(current_room['item'])
print("You acquired : ", current_room['item'])
elif current_room['item'] == ['none']:
print("No items to collect in this room")
else:
print('Invalid entry. Try again.')
I probably did not need to copy in the whole bit. Mainly you would want to focus in on the block of code at the end that checks to see if the player has already picked up an item and if so, remind the player that they already possess the item.
Give that a try and see if it meets the spirit of your project.
Try:
# The dictionary links a room to other rooms and provides info if there
# is an item in the room along with its status ('noItm':True means item
# was already taken):
rooms = {
"Crew Quarters" : {'East' : 'Ship Storage',
'South': 'Operations Deck',
'noItm': True},
"Ship Storage" : {'West' : 'Crew Quarters',
'South': 'Power and Oxygen Control',
'Item' : 'Spare O2 Tank',
'noItm': False},
"Operations Deck" : {'North': 'Crew Quarters',
'East' : 'Power and Oxygen Control',
'South': 'Crew Training Chamber',
'West' : 'Captain Quarters',
'Item' : 'Head Lamp',
'noItm': False},
"Power and Oxygen Control": {'North': 'Ship Storage',
'West' : 'Operations Deck',
'South': 'Infirmary',
'noItm': True},
"Captains Quarters" : {'East' : 'Operations Deck',
'South': 'Armory',
'Item' : 'Key to POC',
'noItm': False},
"Armory" : {'North': 'Captains Quarters',
'East' : 'Crew Training Chamber',
'Item' : 'Laser Rifle',
'noItm': False},
"Crew Training Chamber" : {'North': 'Operations Deck',
'East' : 'Infirmary',
'West' : 'Armory',
'Item' : 'Space Suit',
'noItm': False},
"Infirmary" : {'North': 'Power and Oxygen Control',
'West' : 'Crew Training Chamber',
'Item' : 'Med-kit',
'noItm': False}
}
# List of commands for movement or to exit the game
directions = ['North', 'South', 'East', 'West']
exit_game = ['e', 'exit', 'q', 'quit']
inv = ['i', 'inv']
get_item = ['get']
inv_list = []
# Current / starting room
c_room = 'Crew Quarters'
# print the game name, commands, and objectives.
print("Spaceship Text Adventure")
print("There's been a breach in the Power and Oxygen Control room on the ship!",
"Take care of the threat!")
print("Collect 6 items to defeat the anomaly or let the ship be taken over!")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
print("To check your inventory: 'inv'")
print("To exit the game: 'e' or 'exit'")
# Game Loop
while True:
print('\nYou are in the', c_room)
command = input("\nWhat would you like to do? ")
if len(command) >= 2 and command[0:2] == 'go':
direction = command[3:]
if direction in directions:
if direction in rooms[c_room]:
c_room = rooms[c_room][direction]
if rooms[c_room]['noItm'] is False:
print(c_room)
print(f"There is '{rooms[c_room]['Item']}' in this room.")
else:
if 'Item' in rooms[c_room]:
print("You've already taken the item from this room.")
else:
print('You cannot go that way')
elif len(command) > 10 and command[0:3] in get_item:
item_in_room = rooms[c_room]['Item'] if 'Item' in rooms[c_room] else None
item_to_get = command[5:-1]
if rooms[c_room]['noItm'] is False and item_to_get == item_in_room:
inv_list.append(item_in_room)
rooms[c_room]['noItm'] = True
print(f"You have got '{item_in_room}'")
else:
print(f"There is no '{item_to_get}' in this room")
elif command in inv:
print(inv_list)
elif command in exit_game:
print('You have exited the game. Thank you for playing!')
break
else:
print('Invalid command, try again!')
I have added a new key about the existence of an item to the dictionaries in rooms dictionary allowing to add the code for taking items from a room.

Unable to Move Room to Room in text-based game for IT Python Class

''' I've been working on this for about two weeks now, I can't seem to figure out the logic for the code to properly work and I'm having trouble understanding how to properly pull a key or value from a dictionary. Please note I'm a beginner and some of the concepts just go over my head. '''
''' Below is my code and one of the many errors I have received. Any guidance would be appreciated. '''
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location:
if direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for i in range(100):
for j in range(1000000):
pass
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' )
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction.lower() == [location][items_needed].lower():
if items_needed[location] not in inventory:
inventory.append(items[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction == 'North' or direction == 'South' or direction == 'East' or direction == 'West':
new_location = get_new_location((location, direction))
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')
'''
Error:
Welcome to Camp Crystal Lake!!
You are able to move North, South, East, West, but Jason Voorhees is lurking around.
You will need to collect all 6 items to escape Jason's wrath
If you want to leave the camp immediately, type Exit otherwise enjoy the game!
You are currently at the Camp Crystal Lake Office
Which way do you want to go: -->south
You want to go Camp Crystal Lake Office
Traceback (most recent call last):
File "C:\Users\jr0sa_000\PycharmProjects\pythonMilestone_v1\Project 2.py", line 66, in
if direction.lower() == [location][items_needed].lower():
TypeError: list indices must be integers or slices, not dict
This location has ('Camp Crystal Lake Office', {'Main Entrance': 'rifle', 'Mess Hall': 'Flash Light', 'Creepy Forest': 'Battery', 'Higgins Haven': 'Car', 'Packanack Lodge': 'Running Sneakers', 'Camping Area': 'Bear Trap'})
Your inventory has []
You already have that in your inventory [] # '''
new_location = get_new_location((location, direction))
should be
new_location = get_new_location(location, direction)
Also fixed issue with pointer being incorrect.
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location and direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for _ in range(100):
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' ).lower()
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction == rooms[location]:
if items_needed[location] not in inventory:
inventory.append(items_needed[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction in ['North', 'South', 'East', 'West']:
new_location = get_new_location(location, direction)
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')
I think you meant direction == rooms[location] instead of if direction.lower() == [location][items_needed].lower():
rooms = {
'Camp Crystal Lake Office': {'South': 'Packanack Lodge', 'East': 'Creepy Forest',
'North': 'Main Entrance', 'West': 'Mess Hall'},
'Main Entrance': {'South': 'Camp Crystal Lake Office', 'East': 'Abandoned Shack'},
'Abandoned Shack': {'Jason Voorhees'},
'Mess Hall': {'East': 'Camp Crystal Lake Office'},
'Creepy Forest': {'North': 'Higgins Haven', 'West': 'Camp Crystal Lake Office'},
'Higgins Haven': {'South': 'Creepy Forest'},
'Packanack Lodge': {'East': "Camping Area", 'North': 'Camp Crystal Lake Office'},
'Camping Area': {'West': 'Packanack Lodge'}
}
items_needed = {
'Main Entrance': 'rifle',
'Mess Hall': 'Flash Light',
'Creepy Forest': 'Battery',
'Higgins Haven': 'Car',
'Packanack Lodge': 'Running Sneakers',
'Camping Area': 'Bear Trap'
}
def game_play_rules():
print('Welcome to Camp Crystal Lake!!')
print('You are able to move North, South, East, West, but Jason Voorhees is lurking around.')
print("You will need to collect all 6 items to escape Jason's wrath")
print("If you want to leave the camp immediately, type Exit otherwise enjoy the game!")
# create function to change the location
def get_new_location(location, direction):
new_location = location
for i in rooms:
if i == location and direction in rooms[i]:
new_location = rooms[i][direction]
return new_location
game_play_rules()
location = 'Camp Crystal Lake Office'
inventory = []
while True:
print('\nYou are currently at the ', location) # shows player where they are starting
if location == 'Abandoned Shack':
print("You walked into Jason's shack, better luck next summer.", end= '')
for _ in range(100):
print('.', end=' ', flush = True)
print()
if len(inventory) == 6:
print("You collected all items and were able to escape - enjoy the rest of your summer")
else:
print("Welp, you failed to collect all the items, game over")
break
direction = input('Which way do you want to go: -->' ).lower()
print('You want to go ', (get_new_location(location, direction)))
print(f'\nThis location has ',(location, items_needed))
print('Your inventory has ', inventory)
print('\nYou already have that in your inventory', inventory)
if direction == rooms[location]:
if items_needed[location] not in inventory:
inventory.append(items_needed[location])
continue
direction = direction.capitalize()
if direction == 'Exit':
exit(0)
if direction in ['North', 'South', 'East', 'West']:
new_location = get_new_location((location, direction))
if new_location == location:
print('I would not wander to far if I were you.')
else:
location = new_location
else:
print('Wrong way!!')

Text Based game for IT-140 class. How to display contents of rooms and make get function work for items and display inventory

I'm having some issues with displaying the item in each room and when user issues get command there is a key error. I'm brand new to coding and this is my first course final project. I've been able to find most answers on this site but can't seem to fix this one. Any help is greatly appreciated. Thanks.
Here is my code
rooms = {'Hallway': {'South': 'Holding Cell', 'North': 'Armory', 'West': 'Office',
'East': 'Bathroom', 'contents': 'none'},
'Armory': {'East': 'Supply Room', 'South': 'Hallway', 'contents': 'Revolver'},
'Supply Room': {'West': 'Armory', 'contents': 'Herb'},
'Bathroom': {'West': 'Hallway', 'contents': 'Bandage'},
'Office': {'East': 'Hallway', 'South': 'Captains Office', 'contents': 'key'},
'Captains Office': {'North': 'Office', 'contents': 'Body Armor'},
'Holding Cell': {'North': 'Hallway', 'South': 'Lobby', 'contents': 'Shotgun'},
'Lobby': {'North': 'Holding Cell', 'West': 'West Exit', 'contents': 'none'},
'West exit': {'East': 'Lobby', 'contents': 'Zombie', 'text': 'This is the exit!
Kill the Zombie!'}} # The dictionary links a room to other rooms.
directions = ['North', 'South', 'East', 'West']
currentRoom = rooms['Hallway'] # Start the player in the Hallway.
Inventory = []
def show_instructions():
# print a main menu and the commands
print('-------------------------------------------------------')
print('A car just crashed into the lobby doors!')
print('The driver exits with fatal injuries but is slowly moving to attack you.')
print('You dodge and trap the Zombie in the West Exit! That is your only escape
route!')
print('You run to the Hallway to think.')
print('Find 6 items that will help you kill the Zombie and escape!')
print('Move commands: North, South, East, West,and exit. case sensitive')
print("Add to Inventory: get 'contents'")
print('Enter your move or exit the game. -> ')
print('-------------------------------------------------------')
show_instructions()
contents = currentRoom['contents']
def get_item(currentRoom):
if 'contents' in rooms[currentRoom]:
return rooms[currentRoom]['contents']
else:
return 'This room has no item!'
command = input()
while command.lower() != 'exit':
print("you entered the % s" % currentRoom[command]) # display current location
print("you see " %currentRoom[contents]) # display room contents
command = input('\nWhat do you do? ').strip() # get user input
if command in directions:
if command in currentRoom:
currentRoom = rooms[currentRoom[command]]
else:
# bad movement
print("There is nothing that way, try again.")
elif command.lower().split()[0] == 'get':
contents: " ".join(command.lower().split()[1:])
if contents in currentRoom['contents']:
Inventory.append(item)
print('You grabbed {}.'.format(currentRoom['contents']))
else:
print("I don't see that here.")
elif currentRoom[command] == 'West Exit':
print('You have made it to the West Exit and killed the Zombie!')
quit()
currentRoom = rooms[currentRoom[command]]
while currentRoom in ['West Exit']:
if len(Inventory) == 6:
print('You collected all of the items, and Killed the Zombie!')
else:
print('It looks like you have not found everything, you lose!')
break
print('Umbrella nuked Raccoon City now that you have quit.')

How to pull values from a dictionary with duplicate keys

I'm working on a text-based adventure game where the player moves between rooms and collects items. 'items' is a duplicate key. When I run my program, it's pulling the last value of 'item', instead of the one that pairs to the location. Here is my code:
#Stephanie Rivera
rooms = {
'Foyer': {'North': 'Kitchen', 'item': 'Pocket Watch', 'East': 'Library', 'item': 'Diary Page'},
'Library': {'West': 'Foyer'},
'Kitchen': {'West': 'Living Room', 'item': 'Ripped Photo', 'East': 'Bedroom',
'North': 'Turret', 'South': 'Foyer'},
'Living Room': {'East': 'Kitchen'},
'Bedroom': {'North': 'Attic', 'item': 'The Shadow Man', 'West': 'Kitchen'},
'Attic': {'South': 'Bedroom', 'item': 'Book of Matches'},
'Turret': {'East': 'Cellar', 'item': 'Ouija Board', 'South': 'Kitchen'},
'Cellar': {'West': 'Turret', 'item': 'Lantern'}
}
print('Welcome to The Shadow Man Text Adventure Game.')
print('Collect 6 items to win the game, or be defeated by The Shadow Man.')
print('Move commands: North, South, East, West.')
print("To add items to inventory, enter: Get 'item'.")
location = 'Foyer'
inventory = []
player_move = ''
item = ''
def show_instructions():
#print instructions
print('You are in the', location)
print('Inventory:', inventory)
print('___________')
def player_location():
#print player's location on the map
print('You are in the', location)
def player_inventory():
#print player's inventory
print('Inventory:', inventory)
print('___________')
def player_input():
print('Enter a move:')
player_move = input()
show_instructions()
print('You are lost in the woods. You see a house with a light on up ahead. You decide to enter the house.')
while len(inventory) < 6:
player_move = input('Enter a move: ' )
for k in rooms[location].keys():
if player_move == k:
value = [rooms[location].get('item')[]]
location = rooms[location][player_move]
player_location()
print('You see a', *value)
player_input()
First of all, there cannot be duplicate keys in a dictionary.
So, if you want to store multiple values, use a list and keep appending to that list.
rooms = {
...
...
'Cellar': {'West': 'Turret', 'item': ['Lantern', 'Book', 'blah', 'blah']}
}

Can't start the game and don't know how to add inventory

I have to make a text based game for a final project. The goal is to pick up 6 items and to move from room to room. I'm still very new at this and would like some help! I can't seem to call the functions and I don't know how to add an inventory. Here is my current code:
def show_instructions():
#print a main menu and the commands
print("Thousand Year Vampire")
print("Collect 6 items to defeat the vampire or be destroyed by her.")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
def showStatus(current_room, inventory, rooms):
#print the player's current location
#print the current inventory
#print an item if there is one
def main():
#define inventory and dictionary linking other rooms
rooms = {
'Entry Way': { 'North': 'Stalagmite Cavern'},
'Stalagmite Cavern': {'North': 'Grand Cavern', 'South': 'Entry Way', 'item': 'torch'},
'Grand Cavern': {'North': 'Hallway', 'East': 'Armory', 'West': 'Bedroom', 'South': 'Stalagmite Cavern', 'item': 'cross'},
'Armory': {'North': 'Treasure Trove', 'West': 'Grand Cavern', 'item': 'Stake'},
'Treasure Trove': {'South': 'Armory', 'item': 'silver'},
'Bedroom': {'North': 'Storage', 'East': 'Grand Cavern', 'item': 'elaborate comb'},
'Storage': {'South': 'Bedroom', 'item': 'mirror'},
'Hallway': {'North': 'Cliff Top', 'South': 'Grand Cavern'},
'Cliff Top': {'South': 'Hallway', 'item': 'Orla'}
}
# setting up inventory
inventory = []
# setting the starting room
starting_room = 'Great Hall'
# set current room to starting room
current_room = starting_room
while True:
print("\nYou are currently in {}".format(current_room))
move = input("Enter 'go North/South/East/West' to move or 'Exit': ").split()[-1].capitalize()
# user to exit
if move == 'Exit':
current_room = 'exit'
break
# a correct move
elif move in rooms[current_room]:
current_room = rooms[current_room][move]
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever
#show game instructions
show_instructions()
This is not the final answer but I wanted to show you the changes you can make to the code to get the program to work.
This is just restructuring your code. It is not the solution. Once we understand what the problem is, I can help add to this to solve for it.
def show_instructions():
#print a main menu and the commands
print("Thousand Year Vampire")
print("Collect 6 items to defeat the vampire or be destroyed by her.")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
def showStatus(current_room, inventory, rooms):
#print the player's current location
#print the current inventory
#print an item if there is one
#define inventory and dictionary linking other rooms
rooms = {
'Entry Way': { 'North': 'Stalagmite Cavern'},
'Stalagmite Cavern': {'North': 'Grand Cavern', 'South': 'Entry Way', 'item': 'torch'},
'Grand Cavern': {'North': 'Hallway', 'East': 'Armory', 'West': 'Bedroom', 'South': 'Stalagmite Cavern', 'item': 'cross'},
'Armory': {'North': 'Treasure Trove', 'West': 'Grand Cavern', 'item': 'Stake'},
'Treasure Trove': {'South': 'Armory', 'item': 'silver'},
'Bedroom': {'North': 'Storage', 'East': 'Grand Cavern', 'item': 'elaborate comb'},
'Storage': {'South': 'Bedroom', 'item': 'mirror'},
'Hallway': {'North': 'Cliff Top', 'South': 'Grand Cavern'},
'Cliff Top': {'South': 'Hallway', 'item': 'Orla'}
}
# setting up inventory
inventory = []
# setting the starting room
starting_room = 'Hallway'
# set current room to starting room
current_room = starting_room
#show game instructions
show_instructions()
while True:
print("\nYou are currently in {}".format(current_room))
move = input("Enter 'go North/South/East/West' to move or 'Exit': ").split()[-1].capitalize()
# user to exit
if move == 'Exit':
current_room = 'exit'
break
# a correct move
elif move in rooms[current_room]:
current_room = rooms[current_room][move]
# incorrect move
else:
print("You can't go that way. There is nothing to the {}".format(move))
#loop forever

Categories

Resources