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')
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
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
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 coding project for class, which requires the user to be able to move between rooms. I'm having an issue with one specific part of the code. I can't figure out how to pull the room name from the dictionary. I can get the rest to work. The line I need help with is "('You are in the {}.'.format(player_room[]))". Here is my code:
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
while player_move != 'Exit':
if player_move in moves:
if player_move in player_room:
player_room = rooms[player_room[player_move]]
print('You are in the {}.'.format(player_room[]))
print('Enter a move:')
player_move = input()
elif player_move not in player_room:
print('Invalid move.')
print('Enter a move:')
player_move = input()
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.