2

I want to make a game where you have 5 seconds to input the result, if not, you fail. But I have reached a point where I don't know how to stop waiting for the user to input the number.

My environment is Windows. Up until now I have the following code:

import time
import numpy as np

print("""Let's start the game!""")

# Inputs
Finish = True
puntos_totales = 0
maximo = int(input('Maxim number of the range='))
minimo = int(input('Minim number of the range='))

# Game loop
while Finish:

    num1 = np.random.randint(minimo,maximo)
    num2 = np.random.randint(minimo,maximo)
    correct = num1 * num2
    seconds = time.time()

    print("{} x {} = ".format(num1,num2))
    number = input("")

    if number == 'Finish':
        Finish = False
    else:
        number = int(number)

    puntos = len(str(correct))

    if number == correct and Finish:
        print("Corect")
        if time.time()-seconds < 5:
            puntos_totales = puntos_totales + puntos
            print("Points = {} \nTotal points = {}".format(puntos,puntos_totales))
    elif Finish:
        print("Incorrect")
        print("The correct number is = {}".format(correct))

    if time.time()-seconds > 5:
        print('Time out')

Thanks!

EDIT: I am on Windows this is because the suggested solution with signal.SIGALRM doesn't work.

Ruben_phy
  • 73
  • 6
  • Try [`break`](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops) – zvone Sep 21 '19 at 17:04
  • Break won't do anything, it needs to be a timer or a separate thread because `input()` is a blocking call. – ggorlen Sep 21 '19 at 17:11
  • 2
    Possible duplicate of [Keyboard input with timeout?](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout) and https://stackoverflow.com/questions/15528939/python-3-timed-input/15533404#15533404 – ggorlen Sep 21 '19 at 17:12
  • @ggorlen I tryed but but it doen't work, I think it is because signal.SIGALRM doesn't work for windows. – Ruben_phy Sep 21 '19 at 17:17
  • There are a lot of answers in those threads--13 in all. Surely, something from there should work. Mentioning that you're on Windows is useful, though. – ggorlen Sep 21 '19 at 17:18
  • Also take a look at something like https://stackoverflow.com/questions/29081929/prompt-for-user-input-using-python-asyncio-create-server-instance. – ggorlen Sep 21 '19 at 17:47
  • I have try a lot of them for now no one work as I want, for example the one you provide https://stackoverflow.com/a/15533404/11966948 doesn't jump over the input line, only wait until the user input the data and after that says "Sorry, times up". – Ruben_phy Sep 21 '19 at 17:47

0 Answers0