New to Python and writing a simple text-based game. I am trying to account for both invalid user input and unavailable options. I have created a while loop that is functional - but messy. Any guiding lights for a cleaner way to do this? I have tried using the 'or' option to combine the main while loops and simply change the response(invalid/unavailable) based on the condition, but it wouldn't work at all - not really sure why either. for reference, I am using dictionaries to create the conditions and the user function choose_dir() to return a user input for user_dir.*
def change_room():
choose_dir()
# FIXME
while user_dir not in ['N', 'S', 'E', 'W']:
print("Invalid entry.")
choose_dir()
else:
while rooms[current_room][user_dir] == 'None':
print("Can't go that way.")
choose_dir()
while user_dir not in ['N', 'S', 'E', 'W']:
print("Invalid entry.")
choose_dir()
Use a single loop, not all these nested if
and loops. In your code, if the user chooses a direction that leads to None
in the last call to choose_dir()
, it won't detect that.
def change_room():
while True:
choose_dir()
if user_dir not in ['N', 'S', 'E', 'W']:
print("Invalid entry.")
elif rooms[current_room][user_dir] == 'None':
print("Can't go that way.")
else:
return rooms[current_room][user_dir]
BTW, it would be better if choose_dir()
returned the chosen direction, rather than using the global variable user_dir
.