I'm pretty new to Python and would like to write a (not computer) language trainer for my students. Just something like where a timer runs in the background and the student has to input words quickly to slow down/revert the countdown - otherwise the countdown reaches zero and displays some "game over" message. (Just like when a special agent has to defuse a bomb while the timer races towards zero.)
There are tons of explanations of threading which sounds like the right way to do it, sure, but so far I haven't found anything where a timer is combined with a (time-limited) raw_input
. Could any of you pros give me a pointer to the tutorial/discussion I have overlooked?
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()
You don't have to do it via threading, you could in a single thread run through your 'logic' at a specific frequency and each iteration recalculate the countdown via a time-delta method. This is how many video games are produced.
Lets say you run this pseudo-code method at 60hz:
delta = timenow-timelast;
countdown -= delta;
if(input)
processInputHere;
You should be able to convert the pseudo-code to python code to make it work