In case of a simple game, you could just rely on prompting user all the time and checking if he responds with Q
or other stuff. (So, the input is synchronous to the program.)
In this case you could go with the Dan Coates' answer. Though, I would extend his preprocess_user_input
function to handle the whole prompt sequence:
import sys
def user_input(prompt):
"""user_input(prompt)
prompt -- string to prompt the user with
returns the user's answer to the prompt
or handles it in special cases
"""
inp = raw_input(prompt)
if inp.strip().upper() == "Q":
print("Bye, gamer!")
sys.exit()
return inp
# and use this function everywhere now
begin = user_input("Would you like to start the game?")
if begin.strip() not in ("yes" , "y" , "Yes" , "Y" ):
print("Ok, maybe next time...")
sys.exit()
player_name = user_input("What would you like to name your character?")
print("Welcome " + player_name.capitalize())
while True:
# now we are in the game
act = user_input("People are celebrating on the north, yelling 'Selecao! Parabens!'\nWould you like to go north?")
...process the act...
-- and so on.
You might want to add more options for special cases. And then you need more if
branches. And you might wonder "How to do case
in Python?". The answer is: "do it with dictionaries". And it is a good way to do it. (In fact, one could build the whole game on dictionaries of options for each situation the user is in.)
But in case of asynchronous input (so, when user presses the keys on his own, without the program prompting him and expecting for input) it is not simple. The easiest way to quit a running Python program is by pressing Ctrl + C. It will send a SIGINT
signal to the program. Which Python converts into an exception, called KeyboardInterrupt
. (Not sure about signals in Windows, but for Python it should be the same on any OS.) If an exception is not captured by try..except
it exits the program with the prompt of the exception. If you need to -- you can capture it and do what you want. (Print a message "Bye, gamer!" and exit the program. This quiestion is another example.)
But for capturing any custom key combination pressed probably one needs a bit more involved method.