我对Python很陌生,想为我的学生编写一个(非计算机)语言培训师。就像计时器在后台运行的地方一样,学生必须快速输入单词以减慢/恢复倒计时 - 否则倒计时到达零并显示一些“游戏结束”消息。 (就像特殊的特工必须在定时器向零跑时才能消除炸弹一样。)
有大量的线程解释,这听起来是正确的方法,当然,但到目前为止,我还没有找到任何计时器与(时间限制的)raw_input
相结合的地方。你们中的任何一位专业人士都可以给我一个指向我忽略的教程/讨论的指针吗?
答案 0 :(得分: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()
答案 1 :(得分:0)
您不必通过线程进行操作,您可以在单个线程中以特定频率运行“逻辑”,并且每次迭代都会通过时间增量方法重新计算倒计时。这是制作了多少个视频游戏。
假设您在60hz运行此伪代码方法:
delta = timenow-timelast;
countdown -= delta;
if(input)
processInputHere;
您应该能够将伪代码转换为python代码以使其正常工作