如何限制用户输入的时间 - Python

时间:2016-01-30 21:39:03

标签: python

编辑: 我通过实施@L3viathan's solution解决了这个问题。这是更新的代码:

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()

谢谢大家的贡献。

------编辑结束-------

我一直在寻找Stack Overflow的解决方案但是我找不到任何与我的游戏有关的东西,因此我会道歉这是否是一个重复的问题。

我正在制作一个数学游戏,用户必须回答一个简单的算术问题,每次用户输入正确答案时,分数会增加1。但是,如果用户输入了错误的答案,则游戏结束。

我想为游戏添加超时功能,例如当用户输入其中一个问题的答案时,如果用户需要超过3秒的时间来回答,则游戏结束。有谁知道怎么做?

我能找到的所有解决方案都是针对Unix的,而不是Windows。

这是我的代码:

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()

1 个答案:

答案 0 :(得分:0)

最简单的方法是将呼叫计时到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")

这种方式很简单,但你不能在三秒钟后中止用户输入的能力,只能等待它,然后再看它是否足够快。