I am working on a game where the user travels through rooms by choosing a direction (North, South, East, West). My question is how can i capture an invalid user input? My current code errors out if the user selects a direction where there is no room to go. Here is my code:
current_Room='Torture_Room'
Rooms={
'Torture_Room': {'N': 'Sawdust_Room', 'W':'Boiler_Room', 'S': 'Incinerator','E':'Meat_Grinder'},
'Boiler_room': {'E': 'Torture_Room'},
'Incinerator':{'N': 'Torture_Room', 'E': 'Meat_Hanging_Room'},
'Sawdust_Room': {'E': 'Exit', 'S': 'Torture_Room'},
'Meat_Grinder':{'N': 'Observation_Room', 'W': 'Torture_Room'},
'Observation_Room':{'S':'Meat_Grinder'},
'Meat_Hanging_Room': {'W': 'Incinerator'}
}
#create a way to get user input and keep track of direction
def get_cardinal_direct_from_user():
while True:
direction = input("Which direction would you like to go? >")
if direction.upper() not in ["N", "S", "E", "W"]:
print("Please enter a valid direction.")
else:
return direction.upper()
def main():
current_room = 'Torture_Room'
for i in range(10,1,-1):
inp=get_cardinal_direct_from_user()
current_room=Rooms[current_room][inp]
print('you have entered:', current_room)
print(f'you have {i} chances left')
if __name__ == "__main__":
main()