Home > OS >  How to set input time limit for user in game?
How to set input time limit for user in game?

Time:12-03

I was wondering how I can make a program with input of MAXIMUM 5 seconds(e.g he can send input after 2 seconds) in python I decided to do a SIMPLE game where you basically have to rewrite a word below 5 seconds. I know how to create input and make it wait EXACTLY 5 SECONDS, but what I want to achieve is to set maximum time of input to 5 seconds so if a user types an answer in let's say 2 seconds he will go the next word. Could you tell me the way to achieve my goal. Thanks in advance!


for word in ["banana","earth","turtle","manchester","coctail","chicken"]:

    # User gets maximum of 5 seconds to write the word,
    # if he does it before 5 seconds pass ,he goes to next word (does not have to wait exactly 5 seconds, he   
    # can send input in e.g 2 seconds)      
    # if he does not do it in 5 seconds he loses game and it is finished


    user_input = input(f"Type word '{word}': ")

    #IF the word is correct go to next iteration
    if(user_input==word):
        continue

    #If the word is incorrect finish the game
    else:
        print("You lost")
        break

I tried to do it with threading.Timer() but it doesn't work

import threading

class NoTime(Exception):
    pass

def count_time():
    raise NoTime

for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
    try:


        #Create timer which raises exception after 5 seconds
        timer = threading.Timer(5,count_time)
        timer.start()

        user_input = input(f"Type word '{word}': ")
        #if timer hasn't lasted 5 seconds then destroy it in order to prevent unwanted exception
        timer.cancel()

        if user_input==word:
            print("Correct")
        else:
            print("Incorrect, you LOSE!")
            break

    except NoTime:
        print("You run out of time, you lose")
        break

The error i get

Traceback (most recent call last):
  File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1394, in run
    self.function(*self.args, **self.kwargs)
  File "C:\Users\papit\OneDrive\Pulpit\Programming\Python Bro Course\Math\second\threading_training.py", line 7, in count_time
    raise NoTime
NoTime

CodePudding user response:

=======

To create a program with a maximum input time of 5 seconds in Python, you can use the time and select modules to implement a timeout for the input operation. The time module provides functions for working with time, such as measuring elapsed time, and the select module provides functions for waiting for input from multiple sources, including a timeout.

To create a program with a maximum input time of 5 seconds, you can use the following steps:

Import the time and select modules at the beginning of your program: import time import select Use the time.time() function to get the current time at the start of the input operation: start_time = time.time() Use the select.select() function to wait for input from the user, with a timeout of 5 seconds: timeout = 5 # Set the timeout to 5 seconds input_ready, _, _ = select.select([sys.stdin], [], [], timeout) If the input_ready variable is not empty, which indicates that input was received from the user within the timeout, read the input from the user using the input() function: if input_ready: user_input = input() If the input_ready variable is empty, which indicates that the timeout expired without receiving input from the user, handle the timeout by either displaying an error message or taking another action, as appropriate for your program: else: # Handle the timeout, e.g. by displaying an error message or taking another action Use the time.time() function to get the current time at the end of the input operation, and calculate the elapsed time by subtracting the start time from the end time:

end_time = time.time() elapsed_time = end_time - start_time Use the elapsed time to determine whether the user's input was within the maximum time limit, and take appropriate action, such as displaying the input or moving on to the next word in your game:

if elapsed_time <= timeout: # The user's input was within the time limit, so display it or take another action else: # The user's input was not within the time limit, so handle the timeout Overall, to create a program with a maximum input time of 5 seconds in Python, you can use the time and select modules to implement a timeout for the input operation, and to handle the timeout if the user does not provide input within the maximum time limit. This allows you to ensure that the user's input is received within the specified time limit, and to take appropriate action based on the elapsed time.

CodePudding user response:

import threading

def lost():
    print("You run out of time, you lose")


for word in ["banana", "earth", "turtle", "manchester", "coctail", "chicken"]:

    timer = threading.Timer(5, lost)
    timer.start()

    user_input = input(f"Type word '{word}': ")
    timer.cancel()

    if user_input == word:
        print("Correct")
    else:
        print("Incorrect, you LOSE!")
  • Related