0

I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.

At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.

Here is an idea with pseudo code:

    if (answer = wrong || time = 0)
         lost...
Theof
  • 71
  • 7
  • This is a bit tougher than you think, since it will probably require threading. The easy approach would be to calculate the time taken to answer the question and check whether it was within a threshold. The proper approach would be to research threading. – roganjosh Dec 03 '16 at 16:10
  • Calculating the time taken to answer is not the best idea as the difficulty increases with the points the user collects. Are all AAA titles and not implementing such a feature using threading? @roganjosh – Theof Dec 03 '16 at 16:12
  • I'm afraid I don't understand your last question. But `input` is blocking in Python, so your timer will freeze without threading. I'm going to dupe you an answer since this question comes up a lot so we should direct people back to the source to avoid similar answers. – roganjosh Dec 03 '16 at 16:16

1 Answers1

3

if you want to check if the user took to long when he answered you can use the time module to calculate the diffrence:

start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
   lose()

if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:

timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
    lose() 
DorElias
  • 2,016
  • 11
  • 15