I'm working on a text based game in python and everything seems to be working except for the area which the player will travel to and collect items in. When I start the game, it goes through the intro (which I left out) and then shows me this error along with the player's stats:
item = player(location)
enter code hereline 59, in player
return area[location]['item']
NameError: name 'area' is not defined
I don't really understand how to fix it, I've been trying to define area but I'm still getting the same error.
def rules():
print(' \n Using the commands, North, South, East and West to navigate through the warehouse.')
print('Find your Tiramisu cake! Search the rooms of the warehouse to get your cake!')
print('........Or use Exit to leave the game.')
area = {
'Warehouse': {
'South': 'Basement', 'North': 'Storage Room', 'East': 'Parking Lot', 'West': 'Dusty Room'
},
'Parking Lot': {'West': 'Warehouse','item': 'key'},
'Basement': {'North': 'Warehouse', 'item': 'Kingpin'},
'Storage Room': {'South': 'Warehouse', 'item' : 'Tiramisu Cake'},
'Dusty Room': {'East': 'Warehouse', 'item': 'Safe' }
}
location = 'Warehouse'
def fetch(location, new_dir):
new_room = location
for i in area:
if i == location:
if new_dir in area [i]:
new_room = area [i][new_dir]
return new_room
def stats(location):
return area[location]['item']
rules()
pockets = []
#loop starts here
while 1:
print('\n***********************************************')
print('You are in the', location)
print('In your pockets you hold', pockets)
print('***********************************************')
item = area[location].get('item')
print('In this room you see', 'item')
if item == 'Kingpin':
print ('Oh no! The Kingpin!!......He pummels you, Game Over')
exit(0)
if item is not None and new_dir == 'You got ' + item:
if item in pockets:
print('This room seems empty.....oh wait you already got that item')
else:
pockets.append
new_dir = input('\n Which direction are you going?: ')
new_dir = new_dir.capitalize
if (new_dir == 'Exit'):
print('Thanks for playing!')
exit(0)
if new_dir == 'North' or new_dir == 'South' or new_dir == 'East' or new_dir == 'West':
new_room = fetch(location, new_dir)
if new_room == location:
print(' \n Invalid move, try another direction.')
else:
location = new_room
if new_dir ==str('get'+ 'item'):
if 'item' in pockets:
print('You found', 'item', '!')
pockets.append(area[location]['item'])
else:
print('Invalid move')
if len(pockets) ==3:
print('You have got what you came for, you win! Thanks for playing!')
exit(0)
break
You haven't passed area to the fecth() and stats() functions.
Either pass it or make it global
Related
I am trying to move between rooms using a dict and I can navigate if the room only has 1 location to move to but when it has more than one I get an error.
# The dictionary links a room to other rooms.
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
def instructions():
print("Milestone for Module 6.")
print("Type 'go' and then the direction want to move in lowercase")
print("You can type exit to leave the game after this menu")
current_room = 'Great Hall'
direction = ''
while True:
print('\nYou are in:', current_room)
direction = input('Move which direction?')
print('You entered:', direction)
if direction == 'quit':
print('Game Exited')
break
elif direction == 'go north':
if 'North' in rooms[current_room].keys():
current_room = str(*rooms[current_room].values())
else:
print('Unable to move to that location, try again.')
elif direction == 'go south':
if 'South' in rooms[current_room].keys():
current_room = str(*rooms[current_room].values())
else:
print('Unable to move to that location, try again.')
elif direction == 'go east':
if 'East' in rooms[current_room].keys():
current_room = str(*rooms[current_room].values())
else:
print('Unable to move to that location, try again.')
elif direction == 'go west':
if 'West' in rooms[current_room].keys():
current_room = str(*rooms[current_room].values())
else:
print('Unable to move to that location, try again.')
else:
print('Invalid, please try again.')
Would like to resolve this error and move rooms correctly.
Traceback (most recent call last):
line 40, in <module>
current_room = str(*rooms[current_room].values())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: decoding str is not supported
When you use str(*rooms[current_room].values()) and if it has more than one value in the dictionary, it will result in a TypeError. So, you should be store the values in the dict and use index to access a particular room, like this:
.
.
elif direction == 'go north':
if 'North' in rooms[current_room].keys():
current_room = rooms[current_room]['North']
else:
print('Unable to move to that location, try again.')
I am currently working on a text based game for a school project. My only issue is that I cannot get my program to print 'Invalid input' when the user input does not include 'Take' and [item name]. So the item is added to inventory as long as the user input is 'Take'.
`
import sys
def start_menu():
# Print start menu and commands
print('<>' * 50) # Print lines to separate text
title = (r"""
╔═╗┬─┐┌─┐┌─┐┌┬┐ ╔═╗┬ ┬┬─┐┌─┐┌┬┐┬┌┬┐ ┌─┐┌─┐ ╔╦╗┌─┐┌─┐┬─┐┌─┐┌─┐┌┐┌
║ ╦├┬┘├┤ ├─┤ │ ╠═╝└┬┘├┬┘├─┤││││ ││ │ │├┤ ║║║├┤ ├┤ ├┬┘├┤ ├┤ │││
╚═╝┴└─└─┘┴ ┴ ┴ ╩ ┴ ┴└─┴ ┴┴ ┴┴─┴┘ └─┘└ ╩ ╩└─┘└─┘┴└─└─┘└─┘┘└┘
""")
print(title)
print('<>' * 50 ) # Print lines to separate text
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of the\n'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.\n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.\n'
'\nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
start_menu()
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan\'s Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan\'s Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan\'s Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, '\n')
# Shows current location and item
if current_room == 'Terrace':
print('You are on the {}.\n'.format(current_room))
if current_room == 'Daenerys Chambers' or current_room == 'Barristan\'s Chambers':
print('You are in {}.'.format(current_room))
if item not in inventory:
print('Item:', item, '\n')
else:
print('You have collected all of the items in this room.\n')
elif current_room != 'Terrace':
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
if item not in inventory:
print('Item:', item, '\n')
else:
print('You have collected all of the items in this room.\n')
# Display user input
user_input = input('Enter your move:' + '\n' + '> ') # Movement control
print('') # Space for visual formatting
user_input = user_input.capitalize() # Capitalize user input to match dictionary
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can\'t go there!')
print('<>' * 50)
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid input\n')
if current_room != 'Terrace' and current_room != 'Dragon Pit':
item = rooms[current_room]['item']
# Update inventory
if 'Take' in user_input and current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
if current_room == 'Terrace' and 'Take' in user_input:
print('There is no item here!')
print('<>' * 50)
# Game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('\nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
restart_game()
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('\nYou died.')
print('Collect all six items before facing the Dragons...')
restart_game()
def restart_game():
# Restart or exit game
restart = input('Play again? (y,n):\n> ')
if restart == 'y':
start_menu()
gameplay_loop()
if restart == 'n':
print('Goodbye.')
sys.exit()
else:
print('Invalid input')
restart_game()
gameplay_loop()
`
I tried adding this to my code but it still just accepts 'Take' for user input.
`
# invalid command
elif ('Take'+item) not in user_input:
print('Invalid input\n')
`
This operates the way you expect. I've made several changes in the organization here. I have removed all of your "automatic capitalization", so you must type the command exactly. I have removed all of your recursive calls and replaced them with loops -- this is not a proper use of recursion.
I also deleted your block title because I didn't want to deal with the character set. You can add that back in.
import sys
def start_menu():
# Print start menu and commands
print('<>' * 50)
print('You are a Spy visiting the Great Pyramid of Meereen. You must make your way from the top of the\n'
'Pyramid to the Dragon Pit. Collect all of the items along the way to help defeat the two Dragons.\n'
'If you are successful you will put an end to Queen Daenerys reign and save the Seven Kingdoms.\n'
'\nHappy Adventuring!')
print('<>' * 50)
print('Input move: North, South, East or West')
print('Input "Take [item name]" to add item to inventory')
print('Input "Exit" to quit game')
print('<>' * 50)
# Dictionary of rooms and items
rooms = {
'Terrace': {'East': 'Daenerys Chambers'},
'Daenerys Chambers': {'West': 'Terrace', 'East': 'Barristan\'s Chambers', 'South': 'Royal Chambers',
'item': 'Dragon Necklace'},
'Barristan\'s Chambers': {'West': 'Daenerys Chambers', 'item': 'Barristan\'s Sword'},
'Royal Chambers': {'North': 'Daenerys Chambers', 'South': 'Torture Cells',
'West': 'Audience Chamber', 'East': 'Stables', 'item': 'Milk of the Poppy'},
'Audience Chamber': {'East': 'Royal Chambers', 'item': 'Torch'},
'Stables': {'West': 'Royal Chambers', 'item': 'Health Potion'},
'Torture Cells': {'North': 'Royal Chambers', 'East': 'Dragon Pit', 'item': 'Magic Potion'},
'Dragon Pit': {'West': 'Torture Cells', 'Item': 'Dragons'}
}
def gameplay_loop():
move_direction = ['North', 'South', 'East', 'West']
inventory = []
current_room = 'Terrace'
# Gameplay loop
while True:
# Display Inventory
print('Inventory', inventory, '\n')
if current_room == 'Terrace':
print('You are on the {}.\n'.format(current_room))
else:
print('You are in the {}.'.format(current_room))
if current_room == 'Torture Cells':
print('A sign reads: "Beware of Dragon Pit: East"')
item = None
if 'item' in rooms[current_room]:
item = rooms[current_room]['item']
if item in inventory:
print('You have collected all of the items in this room.\n')
item = None
else:
print('Item:', item, '\n')
# Display user input
user_input = input('Enter your move:' + '\n' + '> ') # Movement control
print('') # Space for visual formatting
# user_input = user_input.title() # Capitalize each word
print('<>' * 50)
if user_input in move_direction:
user_input = user_input
if user_input in rooms[current_room].keys():
current_room = rooms[current_room][user_input]
print(current_room)
print('<>' * 50)
else:
# for invalid movement
print('You can\'t go there!')
print('<>' * 50)
continue
# Check for exit command
elif user_input == 'Exit':
print('Thank you for playing!')
print('<>' * 50)
break
# invalid command
elif 'Take' not in user_input:
print('Invalid input\n')
continue
# What item did they want?
want = user_input[5:]
if want != item:
print("That item is not available.")
continue
# Update inventory
if current_room != 'Terrace' and item not in inventory:
inventory.append(item)
print('You found:', item)
print('<>' * 50)
# Check for game over
if len(inventory) == 6 and current_room == 'Dragon Pit':
print('\nYou have defeated the Dragons and saved the Seven Kingdoms!')
print('Thanks for playing!')
elif len(inventory) < 6 and current_room == 'Dragon Pit':
print('\nYou died.')
print('Collect all six items before facing the Dragons...')
while True:
# Restart or exit game
restart = input('Play again? (y,n):\n> ')
if restart == 'y':
start_menu()
return True
if restart == 'n':
print('Goodbye.')
return False
print('Invalid input')
start_menu()
while gameplay_loop():
pass
To validate Take + Items, you need to read input and store them somthing like below if i understand correctly .
# Check for Take in input and Item name
elif 'Take' in user_input:
item = user_input[5:]
if item in rooms[current_room].values():
inventory.append(item)
print('You have added {} to your inventory.'.format(item))
print('<>' * 50)
else:
print('You can\'t take that!')
print('<>' * 50)```
My code works fine moving between rooms and collecting items but when player gets to the Food court where the villain is without all 6 items in the inventory it should output the player lost, or if player has all item then player wins. See my code below, I added an "if len(Inventory) == and !=" but it isn't working. Any help is appreciated.
This is my first programing/scripting course I take so I need this code probably needs a lot more work than what I think but this is what I have so far.
#enter code here#
#instructions
print('You are at the mall and there is an Alien in the Food Court that you must defeat!')
print("You can only move around the mall by typing 'North', 'South', 'East', or 'West' when asked for your move. Type 'Exit' at any time to leave the game. ")
print("You need to collect 6 items from 6 different stores to defeat the Alien.")
print("If you get to the Alien without all 6 items in your inventory, you die and lose the game.")
print('Good luck!')
rooms = { 'Marshalls': {'name': 'Marshalls', 'East': 'Miscellaneous', 'North': 'Champs'},
'Miscellaneous': {'name': 'Miscellaneous', 'West': 'Marshalls'},
'Champs': {'name': 'Champs', 'North': 'Pharmacy', 'South': 'Marshalls', 'East': 'Sports', 'West': 'Food Court'},
'Sports': {'name': 'Sports', 'North': 'Verizon'},
'Verizon': {'name': 'Verizon', 'South': 'Sports'},
'Food Court': {'name': 'Food Court', 'East': 'Champs'},
'Pharmacy': {'name': 'Pharmacy', 'East': 'Toys', 'South': 'Champs'},
'Toys': {'name': 'Toys', 'West': 'Pharmacy'},
}
items = {'Miscellaneous': 'Rope',
'Champs': 'Running shoes',
'Sports': 'Baseball bat',
'Verizon': 'Phone',
'Pharmacy': 'Tranquilizer',
'Toys': 'Water gun'
}
direction = ['North', 'South', 'East', 'West'] #how player can move
current_room = 'Marshalls'
Inventory = []
#function
def get_new_statement(current_room, direction):
new_statement = current_room #declaring current player location
for i in rooms: #loop
if i == current_room:
if direction in rooms[i]:
new_statement = rooms[i][direction] #assigning new direction to move player
return new_statement #return
while True:
print('You are in the', current_room, 'store')
print('Current inventory:', Inventory)
print('__________________________')
direction = input('Type an allowed direction to move to another store? or type Exit to leave game: ' )
direction = direction
if (direction == 'exit'):
print('Goodbye, thanks for playing!')
exit()
if (direction == direction):
new_statement = get_new_statement(current_room, direction)
if new_statement == current_room:
print('Move not allowed, try again.')
else:
current_room = new_statement
else:
print('Invalid entry')
#ask to collect item in current room
if current_room in items.keys() and items[current_room] != None and items[current_room] != 'Food Court':
print('You an item: ', items[current_room])
option = input('Do you wish to collect it (y/n): ')
if option[0] == 'y' or option == 'Y':
Inventory.append(items[current_room])
items[current_room] = None
#if player gets to the Food Court then player either win or looses the game
if current_room in items.keys() and items[current_room] == 'Alien':
if len(Inventory) == 6:
print('Congrats you defeated the Alien!!')
elif len(Inventory) != 6:
print("You lost")
print('Goodbye')
break
You need to change the line
if current_room in items.keys() and items[current_room] == 'Alien':
to
if current_room == 'Food Court':
Because current_room isn't in items, so the if statement always goes false. If you put Food Court in items, with alien as its value, then it will ask you if you want to collect it. So you need to just check if the room is Food Court, then it will evaluate to true.
Note: You might want to make it check if direction.lower() is in the room's values, so the user can enter any type of capitalized word and it will move if it can.
So I am trying to design a text based adventure game for one of my classes. I have the movement from room to room down, but have been struggling when it comes to getting items added to the inventory for the escape. At first when I tried to enter "get 'item'" I was prompted with 'invalid move' which was happening because there was an issue with the sequence I was calling my functions. Now that I have everything fixed, the items are automatically being added to the inventory without the user entering the get item function, and every time you enter a room, the item is being added despite it already being in the inventory. Here is my code:
def show_instructions():
print('Escape From Work Text Based Game')
print('Movement commands: South, North, East, West')
print("To pick up an item, type 'get [item]'")
print()
print('Your boss is asking you to come in on your days off. To escape without being seen, you will need to get your'
' vest, backpack, lunchbox, paycheck, name badge, and car keys.')
print('Do not enter the room that has your boss, or you can kiss your days off goodbye!')
def player_stat(current_room, inventory):
print('----------------------')
print('You are in the {}'.format(current_room))
print('Item in this room: {}'.format(rooms[current_room]['Item']))
print('Inventory: ', inventory)
print('----------------------')
def move(direction, current_room, rooms):
if direction in rooms[current_room]:
current_room = rooms[current_room][direction]
else:
print('You run into the wall, customers are staring. Try again.')
return current_room
rooms = {
'Garden Center': {'South': 'Hardware Dept.', 'West': 'Customer Service', 'North': 'HR Office',
'East': 'Storage Room', 'Item': 'None'},
'Customer Service': {'East': 'Garden Center', 'Item': 'lunchbox'},
'Hardware Dept.': {'East': 'Break Room', 'North': 'Garden Center', 'Item': 'backpack'},
'HR Office': {'East': 'Lounge', 'South': 'Garden Center', 'Item': 'paycheck'},
'Lounge': {'West': 'HR Office', 'Item': 'name badge'},
'Break Room': {'West': 'Hardware Dept.'},
'Storage Room': {'West': 'Garden Center', 'North': 'Admin Office', 'Item': 'vest'},
'Admin Office': {'South': 'Storage Room', 'Item': 'keys'}
}
directions = ['North', 'East', 'South', 'West']
current_room = 'Garden Center'
inventory = []
show_instructions()
while current_room != 'Exit':
player_stat(current_room, inventory)
player_move = input('What is your command?: ').lower().title()
if player_move == 'exit':
current_room = 'Exit'
print('Sorry to see you go, play again soon!')
elif player_move in directions:
current_room = move(player_move, current_room, rooms)
item = rooms[current_room].get('Item')
if item is not None and player_move == 'get ' + item:
if item in inventory:
print('You already have this item in your inventory!')
else:
inventory.append(item)
if current_room == 'Break Room':
print('Oh no! You got caught. Have fun working this weekend.')
exit()
else:
print('Invalid move')
And this is what the output looks like after I have moved from a few of the rooms. I don't understand why it is printing invalid move after every move even if it is valid either.
You are in the HR Office
Item in this room: paycheck
Inventory: ['paycheck', 'paycheck']
----------------------
Where would you like to go?: south
Invalid move
----------------------
You are in the Garden Center
Item in this room: None
Inventory: ['paycheck', 'paycheck', 'None']
----------------------
Where would you like to go?: south
Invalid move
----------------------
You are in the Hardware Dept.
Item in this room: backpack
Inventory: ['paycheck', 'paycheck', 'None', 'backpack']
----------------------
I also still have to add a way to exit the game when you win after collecting all 6 items, and i was heading in the direction of 'if inventory == [ all 6 items in list ]: print( you win) followed by exit' Any help anyone has to offer would be greatly appreciated.
Try
#Loop continues if user has not entered 'exit' or inventory is not up to 6 items
while current_room != 'Exit' and len(inventory)!= 6:
player_stat(current_room, inventory)
player_move = input('What is your command?: ').lower().title()
if player_move == 'Exit':
current_room = 'Exit'
print('Sorry to see you go, play again soon!')
exit()
elif player_move in directions:
current_room = move(player_move, current_room, rooms)
item = rooms[current_room].get('Item')
#As the input has .title() this condition will accept input of item in that format
if item is not None and player_move == 'Get ' + item.title():
if item in inventory:
print('You already have this item in your inventory!')
#Was adding repeat items because of prior incorrect indentation
#Correct indentation with the else applying after checking inventory
else:
inventory.append(item)
if current_room == 'Break Room':
print('Oh no! You got caught. Have fun working this weekend.')
exit()
#Replaced the 'else' statement with this so the console doesn't return 'Invalid move' every time
if "get " + item not in player_move and player_move not in directions:
print('Invalid move')
#When loop breaks, user will have won
print("You won!")
Your indentation is wrong. You have this:
if item is not None and player_move == 'get ' + item:
if item in inventory:
print('You already have this item in your inventory!')
else:
inventory.append(item)
but I think you want this:
if item is not None and player_move == 'get ' + item:
if item in inventory:
print('You already have this item in your inventory!')
else:
inventory.append(item)
I need help defining a function that will allow me to access a dictionary key for each room that I enter for a text-based game that I am developing. I have tried doing this in different ways, but am confused about how to make this work.
I have tried creating a global variable that I could use dict.get(), which isn't working, I have tried to create a local variable that would pull the value of the key,value pairs and unfortunately I am just not familiar enough with dictionaries to make this work I guess.
I am not sure how to make this work and I am, quite frankly, getting discouraged.
I am trying to get the player to go from room to room, see an item, and then get it appended to their inventory. This is the part that keeps giving me issues. It says that the variable item is not defined.
# Function to show instructions and welcome the player to the game.
def show_instructions():
print("Welcome to the Saga of Light Text Adventure Game!")
print("Collect 6 items to win the game, or be beaten by The Dark Elf Nebo.")
print("Movement commands: North, South, East, West, or Exit to leave the Game.")
print("Add to Inventory: Get 'Item'")
# Define player location and state current inventory
def player_location():
print('-' * 20)
print('You are in the {}'.format(location))
print('Inventory: ', inventory)
print('-' * 20)
def get_new_location(location, player_move):
new_state = location
if location in rooms:
if player_move in rooms[location]:
new_state = rooms[location][player_move]
return new_state
def get_room_item(location):
item = rooms['Item']
return rooms[location][item]
def main_gameplay():
# Dictionary linking rooms and items obtain in them.
rooms = {
'Main Hall': {'South': 'Bedroom', 'North': 'library', 'East': 'Kitchen', 'West':
'Music Room'},
'Music room': {'East': 'Main Hall', 'Item': 'Music Box'},
'Bedroom': {'North': 'Main Hall', 'East': 'Safe room', 'Item': 'Cloak of
Strength'},
'Safe room': {'West': 'Bedroom', 'Item': 'Bow & Arrows'},
'Dining Room': {'South': 'Kitchen', 'Item': 'The Dark Elf Nebo'},
'Kitchen': {'West': 'Main Hall', 'North': 'Dining Room', 'Item': 'Energy
Drink'},
'Study': {'West': 'Library', 'Item': 'Ring of Light'},
'Library': {'East': 'Study', 'South': 'Main Hall', 'Item': 'Book'}
}
return rooms
rooms = main_gameplay()
# Call for the function to display instructions
show_instructions()
location = 'Main Hall'
player_move = ''
inventory = []
# gameplay loop for game
while len(inventory) < 6:
player_location()
# variables for the starting room and player moves and empty inventory list.
direction = player_move
player_move = input('Which location would you like to go?\n').lower() # Ask player
for location to go.
location = get_new_location(location, player_move)
if player_move == 'Exit': # If Exit is selected, game over.
rooms = 'Exit'
print('Thank you for playing!') # Thank you message for playing
# using if/else statements and dict for rooms and telling players where they are.
if 'Item' in rooms[get_room_item(location)]:
if player_move == ('Get' + 'Item').lower():
inventory = inventory.append('Item')
if location in rooms:
if location == 'Main Hall':
print()
elif location == 'Safe Room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'library':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Music room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Dining room':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Kitchen':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
elif location == 'Study':
print(rooms.get('Item'))
print('You see a ' + 'Item')
print()
if len(inventory) == 6: # Print congratulatory message!
print('Congratulations! You have collected all items and defeated the The
Dark Elf Nebo!')
exit(0)
You have a nested dictionary, so you first need to index by the room, then you can get the item
print(rooms[location]['Item'])
In fact you already do this in your get_room_item function, so you can just use that
def get_room_item(rooms, location):
return rooms[location]['Item']
If you just want to check that a room has an 'Item' at all then just
if 'Item' in rooms[location]: