输入与时限/倒计时[关闭](Input with time limit/countdown [clo

2019-07-17 13:06发布

我是很新,Python和希望写一个(而非计算机)语言培训师为我的学生。 只是像,其中一个计时器在后台运行,学生必须输入单词迅速减缓/恢复倒计时 - 否则倒数至零和“游戏结束”的消息显示一些。 (当一个特殊的代理必须化解炸弹,同时向计时器从0比赛就像)。

有吨线程这听起来像这样做,确保以正确的方式的解释,但到目前为止,我没有发现任何东西,其中一个定时器与一个(有时间限制)相结合raw_input 。 可以在任何你赞成的给我的指针教程/讨论中我忽略了?

Answer 1:

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()


Answer 2:

你不必通过线程这样做,你可以通过你的“逻辑”在特定频率上运行一个线程,并在每次迭代通过时间增量法重新计算了倒计时。 这是许多视频游戏是如何产生。

比方说,你在60Hz运行这个伪代码的方法:

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

你应该能够伪代码转换为Python代码,使其工作



文章来源: Input with time limit/countdown [closed]