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)```
Related
Here is the code I have so far. I am working on a project for school making a texted based game. I am able to input my choices in the game, but I run into an issue when entering the room with the Villain and the game not registering it. I can move from room to room and collect items but it doesn't end the game when I enter the room with the Villain without collecting all the items. please help :)
# A dictionary for a simplified moving between rooms game
# The dictionary links a room to other rooms.
rooms = {
'Stable': {'West': 'Foyer'},
'Foyer': {'South': 'Great Hall'},
'Great Hall': {'South': 'Dining Room', 'East': 'Study', 'West': 'Balcony’, ‘North’: ‘Foyer'},
'Study': {'North': 'Library', 'West': 'Great Hall'},
'Dining Room': {'North': 'Great Hall', 'East': 'Kitchen'},
'Library': {'South': 'Study'},
'Kitchen': {'West': 'Dining Room'},
'Balcony': {'East': 'Great Hall'},
}
items = {
'Foyer': 'Shield',
'Great Hall': 'Sword',
'Study': 'Armor',
'Library': 'Spell Book',
'Dining Room': 'Helmet',
'Kitchen': 'Cooked Chicken',
'Balcony': 'Dark Knight',
}
# Dark Knight is the villain
# Main Title/Menu and Move Commands
print('Dark Knight and the Royal Palace Text Adventure Game')
print('Collect 6 items to win the game, or be beaten by the Dark Knight.')
print('Move Commands: North, South, East, West, Exit')
print('Add to Inventory: get ''')
# Start the player in the Great Hall
state = 'Stable'
# store the items collected so far
inventory = []
# function
def get_new_statement(state, direction):
new_statement = state # declaring
for i in rooms: # loop
if i == state: # if
if direction in rooms[i]: # if
new_statement = rooms[i][direction] # assigning new_statement
return new_statement # return
while True: # loop
print('----------------------------------------------')
print('You are in the', state) # printing state
# display inventory
print('Current inventory: ', inventory)
direction = input('Enter which direction you want to go or enter exit: ') # asking user for input
direction = direction.capitalize() # making first character capital remaining lower
if direction == 'Exit': # if
print('----------------------------------------------')
print('Thank you for playing! Challenge the Dark Knight again soon!')
exit(0) # exit function
if direction == 'East' or direction == 'West' or direction == 'North' or direction == 'South': # if
new_statement = get_new_statement(state, direction) # calling function
if new_statement == state: # if
print('That’s a wall! Try another direction.') # print
else:
state = new_statement # changing state value to new_statement
else:
print('Invalid Command!') # print
# ask to collect item in current room
if state in items.keys() and items[state] != None and items[state] != 'Balcony':
print('This room has ', items[state])
option = input('Do you want to collect it (y/n): ')
if option[0] == 'y' or option == 'Y':
inventory.append(items[state])
items[state] = None
# if we have reached a room then we either win or loose the game
if state in items.keys() and items[state] == 'Dark Knight':
if len(inventory) == 6:
print('Congratulations you have saved the Royal Family!!')
else:
print("You have been defeated!")
print('try again')
break
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 know about .lower() and .upper() but no matter what they don't seem to work and they just cause my directions to not work at all. Any help would be appreciated as this is for a project due Sunday and I'm really stuck. All of my code is as follows:
def menu():
print('*' * 20)
print("InSIDious: Sid & the Commodore 64")
print('*' * 20)
print("Collect the 6 pieces of the Commodore 64 before facing Death Adder.")
print("Otherwise succumb to him and be stuck in this realm forever!")
print("How to play: To move, enter 'go North', 'go East', 'go South', 'go West' or 'Exit'/'exit' to quit playing.")
print("To pick up items, enter 'get Item Name' and it will be added to your inventory.")
print("Good luck!\n")
def Main():
rooms = {
'Court Yard': {'North': 'Great Hall', 'East': 'Bed Chambers', 'South': 'Gate House', 'West': 'Kitchen'},
'Great Hall': {'East': 'Throne Room', 'South': 'Court Yard', 'item': 'Sockets'},
'Bed Chambers': {'North': 'Bathroom', 'West': 'Court Yard', 'item': 'Semiconductors'},
'Gate House': {'North': 'Court Yard', 'East': 'Chapel', 'item': 'Capacitors'},
'Kitchen': {'East': 'Court Yard', 'item': 'Connectors'},
'Throne Room': {'West': 'Great Hall', 'item': 'Resistors'},
'Bathroom': {'South': 'Bed Chambers', 'item': 'Filters'},
'Chapel': ''
}
def user_status():
print('-' * 20)
print('You are currently in the {}'.format(current_room))
print('Inventory:', inventory)
print('-' * 20)
directions = ['North', 'South', 'East', 'West']
current_room = 'Court Yard'
inventory = []
menu()
while True:
if current_room == 'Chapel':
if len(inventory) == 6:
print('-----------------')
print('Congratulations!')
print('-----------------')
print('You can now return home after collecting the 6 pieces of the Commodore 64')
print('& defeating Death Adder!')
print('Thank you for playing!')
break
# Losing condition
else:
print('Oh no! You have been found by Death Adder before acquiring all the items to defeat him!')
print('You are now trapped in this realm forever!')
print('Thank you for playing!')
break
print()
user_status()
dict1 = rooms[current_room]
if 'item' in dict1:
item = dict1['item']
if item not in inventory:
print('You see the {} in this room'.format(rooms[current_room]['item']))
command = input('What would you like to do?\n').split()
if command[0] == 'go':
if command[1] in directions:
dict1 = rooms[current_room]
if command[1] in dict1:
current_room = dict1[command[1]]
else:
print('You cannot go that way.')
elif command[0] in ['exit', 'Exit']:
print('Thank you for playing, play again soon!')
break
elif command[0] == 'get':
if command[1] == item:
inventory.append(item)
print('You picked up the' + item)
else:
print('Invalid command.')
else:
print('Invalid input, try again.')
Main()
I have no idea if this is your problem or not, but when you call lower, make sure it's on the string read as input, and not on the array created by calling .split().
command = input('What would you like to do?\n').lower().split()
might be what you're looking for.
The directions in the directions list are in title case (eg "North"), so neither .upper (which would yield eg "NORTH") nor .lower (which would yield eg "north") make them equal.
command[1].title() will format the input in the same way as the directions in the list. Alternatively, you could store the directions in all-lowercase or all-uppercase and use command[1].lower() or command[1].upper().
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