0

I'm creating a basic game that tests you on your times table. You are under a timer and your score is counted up and displayed at the end.

I can either get the game to run or the timer, but not at the same time. As in to play the game for 30 sec then the game ends.

import time
import random

yn = raw_input("Do you wanna play? y/n  ")
#passed_time = 0

if yn == "n":
    exit()

else:
    timer= raw_input ("type start to begin the 30 sec timer -- ")

num1 =int( random.choice(range(1,13)))    #generating random numbers
num2 =int( random.choice(range(1,13)))


a = str(num1)                            #turning into a string for text print
b = str(num2)
#score = 0

real_answer = num1 * num2
print "What is " + a  + " x " + b + "?"

user_answer = int(raw_input("answer   "))
while user_answer != real_answer:
    print "You are wrong, try again "
    user_answer = int(raw_input("Try again- "))

if timer == ("start"):
    seconds = 5             ##how long the timer should be set to
    for i in range (seconds):
        time.sleep(1)
    print ("time is up")

I would like the program to run for 30 seconds then stop and display results.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • use 2 threads, one will count down 30 seconds and notify the other. https://docs.python.org/2/library/threading.html – sleepyhead Jan 08 '19 at 17:52
  • Possible duplicate of [break the function after certain time](https://stackoverflow.com/questions/25027122/break-the-function-after-certain-time) – glibdud Jan 08 '19 at 18:52

1 Answers1

0

Welcome to stack. So the comments mentioning threads would probably be better in the long term, but this solution is likely easier to understand.

You will need to include this import:

from datetime import datetime

Then change the else statement to this where you ask the user if they would like to play. This will get the current time at the start of the game:

else:
    timer= raw_input ("type start to begin the 30 sec timer -- ")
    t1 = datetime.now()

Then in the while statement you will need to use delta.total_seconds() to get the difference in seconds using another datetime.now() to get the new current time.

while user_answer != real_answer:
    t2 = datetime.now()
    delta = t2 - t1
    if(delta.total_seconds()>=30):
        print "You ran out of time."
        break

This bit of code, uses the t1 start time and the t2 current time. To check if they have ran out of time. You can see where more on this code in this question where it may be more simple to understand. https://stackoverflow.com/a/24260054/1898965

However this will not stop the code right at 30 seconds like you could do with threading. This just checks if each time you ask the user for a new answer if more than 30 seconds has elapsed.

Zack Tarr
  • 851
  • 1
  • 8
  • 28