Short Circuit
Short Circuit

Reputation: 43

Python 3.2 Passive User Input

Is there a way to program a function that takes user input without requesting it? For example, during a game of tic-tac-toe, the user could press "Q" at any time and the program would close?

Upvotes: 1

Views: 515

Answers (2)

Rushy Panchal
Rushy Panchal

Reputation: 17552

Assuming you are just printing the board out (I have a basic Tic-Tac-Toe game that does that), during input you could close it (even though you specifically asked otherwise):

user_option = input("Enter a space to move to, or 'Q' to quit: ")

try:
    if user_option.lower() == 'q': # makes everything lowercase so it is easier to handle
        import sys
        sys.exit("Game Terminated.")
except TypeError:
    # other code

I'm not sure how the player chooses to move, so I used try and except. In my Tic-Tac-Toe game, I have the user input an integer, which corresponds to a space on the board.

Or, you can just have the user press Ctrl+C which is the automatic KeyBoardInterrupt in Python (ends the program).

Upvotes: 0

Fredrick Brennan
Fredrick Brennan

Reputation: 7357

There are a few ways to do this, and they are all different.

If your game is a terminal application using curses, you would catch the q when you call getch(), and then raise SystemExit or simply break out of your while loop that many curses applications use.

Using tkinter or another GUI library, you would bind a key press event to your Frame widget that holds the tic-tac-toe board.

Upvotes: 1

Related Questions