简体   繁体   中英

How to limit time user takes to input - Python

EDIT: I solved this by implementing @L3viathan's solution . Here is the updated code:

import operator
import random
from time import time
import sys

def menu():
    menu = input("\n\n\n--------\n  Menu  \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
    if menu == "1":
        play_game()
    if menu == "2":
        print("Exiting...")
        sys.exit()
    while menu != "1" or menu != "2":
        print("Please enter a valid choice")
        menu = input("--------\n  Menu  \n--------\nPress:\n- (1) to play \n- (2) to exit\n: ")
        if menu == "1":
            play_game()
        if menu == "2":
            print("Exiting...")
            break

def game_over():
    print("Game over.")
    file = open("score.txt", "r")
    highscore = file.read()
    if int(highscore) < score:
        file = open("score.txt", "w")
        file.write(score)
        file.close()
        print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
    else:
        print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))

def play_game():
    print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
    counter = 1 
    score = 0

    while counter == 1:
        ops = {"+":operator.add, 
                "-":operator.sub,
                "x":operator.mul} 
        num1 = random.randint(0, 10) 
        op = random.choice(list(ops.keys()))
        num2 = random.randint(1, 10) 
        print("\nWhat is {} {} {}? ".format(num1, op, num2))
        start = time()
        guess = float(input("Enter your answer: "))
        stop = time()
        answer = ops.get(op)(num1,num2)

        if guess == answer:
            if stop - start > 3:
                print("You took too long to answer that question. (" + str(stop - start) + " seconds)")
                def game_over():
                    print("Game over.")
                    file = open("score.txt", "r")
                    highscore = file.read()
                    if int(highscore) < score:
                        file = open("score.txt", "w")
                        file.write(score)
                        file.close()
                        print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
                    else:
                        print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
                    menu()
                game_over()
                break
            else:
                score = score + 1 
                print("Correct!\nScore: " + str(score))
        else: 
            print("Game over.")
            counter = counter - 1
            file = open("score.txt", "r")
            highscore = file.read()
            if int(highscore) < score:
                file = open("score.txt", "w")
                file.write(score)
                file.close()
                print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
            else:
                print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
        if counter != 1:
            menu()
menu()

Thank you all for your contributions.

------ EDIT END -------

I have been searching Stack Overflow for a solution however I could not find anything which works with my game, therefore I appologise if this is a duplicate question.

I am making a math game where a user has to answer a simple arithmetic question, each time the user enters the correct answer, the score increases by one. However, if the user enters a wrong answer, the game ends.

I would like to add a timeout feature to the game, for example when a user is entering an answer to one of the questions, if the user takes more than 3 seconds to answer, the game ends. Does anyone know how to do this?

All of the solutions I could find were for Unix, not Windows.

Here is my code:

import operator
import random

def play_game():
    print("Type in the correct answer to the question\nYou have 3 seconds to answer each question\nThe game will continue until you answer a question incorrectly") #displays the welcome message
    counter = 1 
    score = 0

    while counter == 1:
        ops = {"+":operator.add, 
                "-":operator.sub,
                "x":operator.mul} 
        num1 = random.randint(0, 10) 
        op = random.choice(list(ops.keys()))
        num2 = random.randint(1, 10) 
        print("\nWhat is {} {} {}? ".format(num1, op, num2))
        guess = float(input("Enter your answer: "))
        answer = ops.get(op)(num1,num2)

        if guess == answer: 
            score = score + 1 
            print("Correct!\nScore: " + str(score)) 
        else: 
            print("Game over.")
            counter = counter - 1
            file = open("score.txt", "r")
            highscore = file.read()
            if int(highscore) < score:
                file = open("score.txt", "w")
                file.write(score)
                file.close()
                print("Score: {}\n\n******************\nNew highscore!\n******************".format(str(score)))
            else:
                print("Score: {}\nHighscore: {}".format(str(score), str(highscore)))
        if counter != 1:
            menu = input("\n\n\nMenu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
            if menu == "1":
                play_game()
            elif menu == "2":
                print("Exiting...")
                break
            while menu != "1" or menu != "2":
                print("Please enter a valid choice")
                menu = input("Menu\n----\nPress:\n- (1) to play again\n- (2) to exit\n: ")
                if menu == "1":
                    play_game()
                elif menu == "2":
                    break
                    print("Exiting...")
play_game()

The easiest way to do this would be to time the call to input :

from time import time

start = time()
answer = input("Answer this in 3 seconds: 1 + 1 = ")
stop = time()

if stop - start < 3:
    if answer == "2":
        print("Correct!")
    else:
        print("Wrong!")
else:
    print("Too slow")

This way is simple, but you couldn't abort the user's ability to input after three seconds, only wait for it and then see if it was fast enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM