当前位置: 代码迷 >> python >> 如何在10秒后强制一些用户输入
  详细解决方案

如何在10秒后强制一些用户输入

热度:38   发布时间:2023-07-14 08:58:41.0

我是一个python的首发,需要一些像游戏这样的测验的帮助。 这是我的代码:

import time
from threading import Timer
import random as rnd

q = ["q1", "q2", "q3"]
a = ["a1    b1    c1", "a2    b2    c2", "a3    b3    c3"]
ca = ["b", "c", "b"]
points = 0


rand_q = rnd.randint(0, len(q) - 1)                                             # Choosing random question
print(q[rand_q] + "\n" + a[rand_q] + "\n")                                      # Asking question and showing answers
time.sleep(0.5)                                                                 # Little pause between prompts

t = Timer(10, print, ['Time is up!'])                                           # Setting up timer
t.start()                                                                       # Start timer
start = time.time()                                                             # Start of time check
answer = input("You have 10 seconds to choose the correct answer.\n")           # User input
if answer is ca[rand_q]:                                                        # Check if answer is correct
    print("Correct answer!")
    points = (points + round(10 - time.time() + start, 1)) * 10                 # Calculate points
else:
    print("Wrong answer!")
t.cancel()                                                                      # Stop timer
print("Points:", points)
input("Press ENTER to quit")

del q[rand_q]                                                                   # Removing the question
del a[rand_q]                                                                   # Removing the answer
del ca[rand_q]                                                                  # Removing the correct answer

当我运行这个时,我可以回答问题并获得积分,但是当我等待计时器时,我得到一个提示说时间到了,但我仍然可以填写并回答问题。

我希望输入在10秒后停止工作,但我似乎无法完成这项工作。 有没有什么办法可以让计时器在“Time is up”提示之上超时所有先前的输入。

我看过更多这样的帖子,但它们看起来已经过时,我没有让它们起作用。

编辑:睡眠命令不起作用。 它会打印一条线,说明为时已晚,但您仍然可以输入答案。 线程计时器也是如此。 我希望在10秒后终止输入命令,但似乎没有Windows的解决方案。

问题是python的输入函数是阻塞的,这意味着在用户输入一些数据之前不会执行下一行代码。 非阻塞输入是很多人一直要求的,但最好的解决方案是创建一个单独的线程并在那里提出问题。 这个问题在文章中得到了回答

此解决方案将起作用,但用户仍需在某个时刻按Enter键才能继续:

import time
import threading

fail = False
def time_expired():
    print("Too slow!")
    fail = True

time = threading.Timer(10, time_expired)
time.start()
prompt = input("You have 10 seconds to choose the correct answer.\n")

if prompt != None and not fail:
    print("You answered the question in time!")
    time.cancel()

你可以做你想做的事,但它变得非常复杂。

  相关解决方案