4

我对 Python 很陌生,想为我的学生写一个(不是计算机)语言培训师。就像计时器在后台运行并且学生必须快速输入单词以减慢/恢复倒计时一样 - 否则倒计时达到零并显示一些“游戏结束”消息。(就像特工必须在计时器趋向零时拆除炸弹一样。)

当然,有很多关于线程的解释听起来像是正确的方法,但是到目前为止,我还没有发现任何将计时器与 (time-limited) 结合使用的东西raw_input。你们中的任何一个专业人士可以给我一个指向我忽略的教程/讨论的指针吗?

4

2 回答 2

4
import threading
import time
import os

def ask():
    """
    Simple function where you ask him his name, if he answers
    you print message and exit
    """
    name = raw_input("Tell me your name, you have 5 seconds: ")
    exit_message = "Wohoho you did it..Your name is %s" % name
    exit(exit_message)

def exit(msg):
    """
    Exit function, prints something and then exits using OS
    Please note you cannot use sys.exit when threading..
    You need to use os._exit instead
    """
    print(msg)
    os._exit(1)

def close_if_time_pass(seconds):
    """
    Threading function, after N seconds print something and exit program
    """
    time.sleep(seconds)
    exit("Time passed, I still don't know your name..")

def main():
    # define close_if_time_pass as a threading function, 5 as an argument
    t = threading.Thread(target=close_if_time_pass,args=(5,))
    # start threading
    t.start()
    # ask him his name
    ask()

if __name__ == "__main__":
    main()
于 2012-12-25T10:23:38.670 回答
0

您不必通过线程来执行此操作,您可以在单个线程中以特定频率运行您的“逻辑”,并且每次迭代都通过时间增量方法重新计算倒计时。这就是制作了多少视频游戏。

假设您以 60hz 运行此伪代码方法:

delta = timenow-timelast;
countdown -= delta;
if(input)
    processInputHere;

您应该能够将伪代码转换为 python 代码以使其工作

于 2012-12-25T10:13:46.260 回答