简体   繁体   English

Python 3.2被动用户输入

[英]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? 例如,在井字游戏中,用户可以随时按“ Q”,程序将关闭吗?

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. 如果您的游戏是使用curses的终端应用程序,则在调用getch()时会捕获q ,然后引发SystemExit或简单地退出许多curses应用程序使用的while循环。

Using tkinter or another GUI library, you would bind a key press event to your Frame widget that holds the tic-tac-toe board. 使用tkinter或其他GUI库,您可以将按键事件绑定到保存tic-tac-toe面板的Frame小部件。

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): 假设您只是将板子打印出来(我有一个基本的Tic-Tac-Toe游戏可以做到这一点),则在输入过程中您可以将其关闭(即使您另有要求):

user_option = input("Enter a space to move to, or 'Q' to quit: ") user_option = input(“输入要移至的空格,或使用'Q'退出:”)

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 . 我不确定玩家如何选择移动,因此我使用了tryexcept 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). 或者,您可以让用户按Ctrl + C ,这是Python中的自动KeyBoardInterrupt (结束程序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM