Moving Between Rooms - python

The code I have is as follows:
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
def show_instructions():
print('The instructions are as follows: go north, go south, go east, go west')
def move_rooms(direction, room='Great Hall'):
if direction == 'go south':
room = 'Bedroom'
return rooms[room]['South']
elif direction == 'go north':
if room == 'Great Hall' or 'Cellar':
return 'Invalid direction please try again.'
return rooms[room]['North']
elif direction == 'go east':
if room == 'Great Hall' or 'Cellar':
return 'Invalid direction please try again.'
return rooms[room]['East']
elif direction == 'go west':
if room == 'Bedroom' or 'Great Hall':
return 'Invalid direction please try again.'
return rooms[room]['West']
currentRoom = 'Great Hall'
gameInstructions = 'The instructions are as follows: go north, go south, go east, go west'
print(gameInstructions)
print(currentRoom)
userDirection = ''
while userDirection != 'exit':
userDirection = input("Pick a direction, or type exit to exit the game.")
if currentRoom == 'Great Hall':
if userDirection == 'go south':
currentRoom = move_rooms(userDirection, currentRoom)
show_instructions()
print(currentRoom)
else:
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
elif currentRoom == 'Bedroom':
if userDirection != 'go north' or 'go east':
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
elif userDirection == 'go north':
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
elif userDirection == 'go east':
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
elif 'Cellar' == currentRoom:
if userDirection != 'go west':
print('Invalid direction. Please pick another direction.')
print(currentRoom)
show_instructions()
else:
currentRoom = move_rooms(userDirection, currentRoom)
print(currentRoom)
show_instructions()
else:
if userDirection == 'exit':
print('Thanks for playing the game!')
break
This is a small part of a larger text based game that I am supposed to develop as part of my college class. The goal of this program is to get user input to move between rooms. I used the template dictionary given and am trying to restrict inputs to the instruction list with the exception of the word 'exit'. So the major issue I am having is how to use the return function properly in the function I created to yield the correct result.
It is giving me a 'KeyError' of 'South' in the console everytime I try to input go south as the first direction. Any help would be appreciated.

Well, to answer your main question of why you are seeing that KeyError, is because you are trying to access a key that doesn't exist for the nested dictionary value of 'Bedroom'. Look at the k-v pair you made for that key.
You would have to do this instead to return the value for 'South' key:
if direction == 'go south':
room = 'Greathall'
return rooms[room]['South']
>>> 'Bedroom'
Just a tip here: why not call the room directly in the dictionary value extraction so instead of defining room as 'Greathall', you could do:
return rooms['Greathall']['South']
Which will give you the same response.

Related

How to add a function get_new_state that takes in (direction_from_user, current_room)?

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

Pyhton Move Between Rooms

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.')

text based python game with functions, function patameters and global variables

I am making a text-based python game for school. They want parameters in the move_room function but that makes it loop the same room. So I tried making current_room = move_rooms(move, current_room, inventory) but if I pick up an item, the program thinks that item is the room. Can someone give me some help with this please?
def give_instructions():
# print game instructions
print("Welcome to the game!\n"
"You were arriving home when attacked by a rival wizard,\n"
"you wake in a strange cell where the walls meet at impossible angles.\n"
"You have a sense of impending doom and a massive headache.\n"
"As your head clears you realize you are in your own home.\n"
"You must collect 7 items to defeat the wizard in your parlor.\n"
"To move type 'go North', 'go South', 'go East' or 'go West'\n"
"To pick up items type 'get' Item name\n"
"To exit type 'Exit'\n")
def show_status(room, stuff, roomsli):
# show player their current status(room, room exits and inventory)
print('You are in {}'.format(room))
print('Inventory:', stuff)
if "Item" in roomsli[room]:
print("{} is in {}".format(roomsli[room].get('Item'), room))
for direction, room in roomsli[room].items():
if direction != 'Item':
print("You can exit {} to {}".format(direction, room))
def move_rooms(move, current_room, inventory):
# controls for room movement and inventory
if move[0] in ['Exit', 'exit']:
# to exit game
current_room = 'Exit'
return current_room
elif move[0] == 'go':
# to change rooms or get error if not a good direction
if move[1] not in rooms[current_room]:
print("Invalid move\n")
elif move[1] in rooms[current_room]:
direction = move[1]
current_room = rooms[current_room][direction]
return current_room
elif move[0] == 'get':
# to get item, add it to inventory, remove it from rooms, or error if wrong item
if move[1] not in rooms[current_room].get("Item"):
print("That item is not in this room\n")
else:
item = rooms[current_room].get('Item')
inventory.append(item)
del (rooms[current_room]['Item'])
return inventory
else:
# if other move is entered
print("Invalid move\n")
if __name__ == '__main__':
# main program
# room dictionary
rooms = {
'Dungeon Cell': {'West': 'Basement'},
'Basement': {'East': 'Dungeon Cell', 'West': 'Cellar', 'North': 'Grand Hall', 'Item': 'Keys'},
'Cellar': {'East': 'Basement', 'Item': 'Amulet'},
'Grand Hall': {'South': 'Basement', 'East': 'Sitting Room', 'West': 'Dining Room', 'North': 'Entryway',
'Item': 'Staff'},
'Sitting Room': {'North': 'Library', 'West': 'Grand Hall', 'Item': 'Cloak'},
'Library': {'South': 'Sitting Room', 'Item': 'Book'},
'Dining Room': {'East': 'Grand Hall', 'North': 'Kitchen', 'Item': 'Dusty Cupcake'},
'Kitchen': {'South': 'Dining Room', 'East': 'Entryway', 'Item': 'Strange Potion'},
'Entryway': {'West': 'Kitchen', 'South': 'Grand Hall', 'East': 'Parlor'},
'Parlor': {'West': 'Entryway'},
'Exit': {'exits the game'}
}
# call for instructions
give_instructions()
# set current room and start inventory
current_room = "Dungeon Cell"
inventory = []
# main game loop
while current_room != 'Exit' or current_room != 'Parlor':
show_status(current_room, inventory, rooms)
move = input("What is your move?\n").split()
current_room = move_rooms(move, current_room, inventory)
# exit game conditional
if current_room == 'Exit':
print('You exited the game. Thanks for playing!')
break
elif current_room == 'Parlor':
# room conditional if wizard in room and inventory full
if len(inventory) == 7:
print("You use your items to defeat the wizard and regain control of your home.\n"
"Congratulations you have won!\n"
"Thanks for playing!")
break
# room conditional if wizard in room and inventory not full
else:
print("The wizard kills you as you are not prepared enough.\n"
"You have lost!\n"
"Thanks for playing!")
break

Python Text Adventure Game

I am creating a text adventure game for IT 140 and I am having a hard time trying to show items in each room. The object is to go from room to room with directional commands and you encounter see an item, pick up the item and keep moving until you have all items to then encounter the villain.
I am currently stuck with a def and having an output stating what is in the room you are currently in and moving then when you move to the next room, you see the item that is in that room and collect them.
this is what I have. Any help would be greatly appreciated! Thank you!
rooms = {
'Main Cavern': {'South': 'Healing Cavern', 'North': 'Flight Cavern', 'West': 'Telekinesis Cavern',
'East': 'Sacred Cavern'},
'Telekinesis Cavern': {'East': 'Main Cavern', 'Item': 'Telekinesis'},
'Flight Cavern': {'South': 'Main Cavern', 'East': 'Primordial Cavern', 'Item': 'Flight'},
'Primordial Cavern': {'West': 'Flight Cavern', 'Item': 'Gem'},
'Strong Cavern': {'South': 'Sacred Cavern', 'Item': 'Strong'},
'Sacred Cavern': {'North': 'Strong Cavern', 'West': 'Main Cavern', 'Item': 'Ancient Book'},
'Healing Cavern': {'North': 'Main Cavern', 'East': 'Cursed Cavern', 'Item': 'Healing'},
'Cursed Cavern': {'West': 'Healing Cavern', 'Item': 'Villain'}
}
current_room = 'Main Cavern'
inventory = []
def get_new_room(current_room, direction):
new_room = current_room
for i in rooms:
if i == current_room:
if direction in rooms[i]:
new_room = rooms[i][direction]
return new_room
def get_item(rooms):
return rooms[current_room]['Item']
def show_instructions():
# print a main menu and the commands
print("Welcome to the Power Balance Text Adventure Game!")
print("")
print("YOu must obtain the Gem and collect 4 abilities to defeat the villain and win the game.")
print("")
print("Move commands: go North, go South, go East, go West")
print("")
print("Add to Inventory: get, item name/ability name")
print("")
print("<< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >< >>")
show_instructions()
Inventory = []
items = ['Telekinesis', 'Flight', 'Gem', 'Strong', 'Ancient Book', 'Healing', 'Villain']
while 1:
print('\nYou are in the', current_room)
print('Inventory:', Inventory)
item = get_item(rooms)
print('You see a ', item)
# will ask user which direction they would like to go
direction = input('\nEnter which direction you\'d like to go or enter exit to end the game: ')
direction = direction.capitalize()
# will display thank you for playing when the user exits
if direction == 'Exit':
print('\nThank you for playing!')
exit(0)
# will display thank you for playing when the user exits
if direction == 'East' or direction == 'West' or direction == 'North' or direction ==
"South":
new_room = get_new_room(current_room, direction)
# an invalid direction by text or if there is no connecting room, will display 'invalid direction'
if new_room == current_room:
print('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('\nThere\'s no cavern in that direction, try again!')
else:
current_room = new_room
else:
print('\nInvalid direction!!')
After running the code myself it seems like the error is occurring here:
Traceback (most recent call last):
File "main.py", line 50, in <module>
item = get_item(rooms)
File "main.py", line 27, in get_item
return rooms[current_room]['Item']
KeyError: 'Item'
A few notes before discussing the error:
Some of the names are being shared globally. For example current_room is a global variable, but also is being passed as an argument. Perhaps you should rename that argument in the function.
There's no need to pass rooms to get_item as it's already accessible in global scope. This kind of mirrors the point made in 1.
For the error, if you check current_room before the line: return rooms[current_room]['Item'] you'll find that it's set to 'Main Cavern'. In your dictionary 'Main Cavern' has no key 'Item', and thus it can not be accessed. Perhaps you could add the 'Items' key to 'Main Cavern' but make the value None if you wish for there to be item there. You could also create an if Statement to check if they key exists before accessing.

Invalid move condition, Python text based game

I need help with a text-based python game, I have done most of the work, I can move between all 3 rooms, there is 'Great hall' at the top then go south 'Bedroom' go east 'Cellar' the I can go back so go west 'bedroom' go north finally to get back to the great hall.
the problem is if I'm in the great hall and type east it skips to cellar instead of saying invalid move there's a wall.
what I'm trying to do
Output that displays the room the player is currently in.
Decision branching that tells the game how to handle the different commands. The commands can be to either move between rooms (such as go North, South, East, or West) or exit.
If the player enters a valid “move” command, the game should use the dictionary to move them into the new room.
If the player enters “exit,” the game should set their room to a room called “exit.”
If the player enters an invalid command, the game should output an error message to the player (input validation).
A way to end the gameplay loop once the player is in the “exit” room
this is the code I have written so far
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
def player_stat():
print("-" * 20)
print('You are in the {}'.format(currentRoom))
print("-" * 20)
currentRoom = 'Great Hall'
player_move = ''
while currentRoom != 'Exit':
player_stat()
player_move = input('Enter your move:\n')
if player_move in ['Exit', 'exit']:
currentRoom = 'Exit'
print('Play again soon')
elif player_move in ['South', "south"]:
currentRoom = 'Bedroom'
elif player_move in ['North', "north"]:
currentRoom = 'Great Hall'
print("You made it back to the Great Hall")
elif player_move in ['East', 'east']:
currentRoom = 'Cellar'
print('YOU MADE IT TO THE CELLAR, try to go back to the Great Hall')
elif player_move in ['West', "west"]:
currentRoom = 'Bedroom'
print("You made it back to the Bedroom")
Please help me
rooms = {
'Great Hall': {'south': 'Bedroom'},
'Bedroom': {'north': 'Great Hall', 'east': 'Cellar'},
'Cellar': {'west': 'Bedroom'}
}
def player_stat():
print("-" * 20)
print('You are in the {}'.format(currentRoom))
print("-" * 20)
currentRoom = 'Great Hall'
player_move = ''
while currentRoom != 'Exit':
player_stat()
player_move = input('Enter your move:\n').lower()
if player_move in ['Exit', 'exit']:
currentRoom = 'Exit'
print('Play again soon')
continue
try:
currentRoom = rooms[currentRoom][player_move]
except Exception:
print("invalid move")
continue
if currentRoom == 'Great Hall':
print("You made it back to the Great Hall")
elif currentRoom == 'Cellar':
print('YOU MADE IT TO THE CELLAR, try to go back to the Great Hall')
print("You made it back to the Bedroom")
I modified your code to utilize the dictionary. It involves nested conditional statements.
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
def player_stat():
print("-" * 20)
print('You are in the {}'.format(currentRoom))
print("-" * 20)
currentRoom = 'Great Hall'
player_move = ''
while currentRoom != 'Exit':
player_stat()
player_move = input('Enter your move:\n').title()
if player_move == 'Exit':
currentRoom = 'Exit'
else:
if player_move in rooms[currentRoom]:
currentRoom = rooms[currentRoom][player_move]
if currentRoom == 'Great Hall':
print("You made it back to the Great Hall")
elif currentRoom == 'Cellar':
print('YOU MADE IT TO THE CELLAR, try to go back to the Great Hall')
else:
print("That is not a valid move, try again.")
print('Play again soon')

Categories