我如何对测验中提出的每个问题设置计时器

  • 本文关键字:问题 计时器 设置 python
  • 更新时间 :
  • 英文 :


我试图创建一个测验,其中一个标准是限制可用于解决测验中每个问题的时间。我查阅了某些教程,但有些教程需要输入x秒才能使计时器停止,而另一些教程看起来更像秒表。。。

我想知道,如果30秒的时间已经结束,我该如何使用后台计时器,它会在问题打印出来后立即计时,并跳到下一个问题?我对定时器功能一无所知,甚至在尝试将它们实现到代码中时都遇到了问题。有人能给我一些建议吗?这样我就可以在实现工作计时器方面取得进一步的进展了?

谢谢!

编辑部分如下:我想在我的编码上实现的计时器:

import time
import threading
def atimer():
print("Time's up.")
a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")

这就是我试图实现定时器的全部代码。我注意到,当我试图将qtimer定义为只打印1或2行语句时,计时器可以工作,但我希望计时器停止并转到第二个问题,或者停止并再次尝试用户重试该问题,所以我试图在定义后附加一堆代码,但它不起作用。我知道我很可能在这里做错了什么,因为我不太熟悉时间或线程函数。有变通办法吗?

def qtimer():
print("I'm sorry but your time is up for this question.")
print("You may have another attempt if you wish to, with reduced marks allocated.")
response1 = input("Type 'Yes' for another attempt, anything else to skip: ")
if response1 == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
class A:
def __init__(self, question, correctAnswer, otherAnswers, difficulty, explanation):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
self.diff = difficulty
self.expl = explanation
qaList = [A("What is COVID-19?", "Coronavirus Disease 2019", ["Wuhan virus", "I don't understand...", "Coronavirus Disease v19"], 1, "Explanation 1"),
A("What describes COVID-19?", "A disease", ["A virus", "A parasite", "A bacteriophage"], 1, "Explanation 2"),
A("What causes COVID-19?", "SARS-CoV-2", ["Coronavirus", "Mimivirus", "Rubeola Virus"], 1, "Explanation 3"),
A("Which of the following is used in COVID-19 treatment?", "Lopinavir / Ritonavir ", ["Midazolam / Triazolam", "Amiodarone", "Phenytoin"], 2, "Explanation 4"),
A("Which of the following receptors is used by COVID-19 to infect human cells?", "ACE-2 Receptors", ["ApoE4 Receptors", "TCR Receptors", "CD28 Receptors"], 3, "Explanation 5")]
corr = 0
marks = 0
random.shuffle(qaList)
for qaItem in qaList:
q_timer = threading.Timer(5.0, qtimer)
q_timer.start()
print(qaItem.question)
print("Possible answers are:")
possible = qaItem.otherAnsw + [qaItem.corrAnsw]
random.shuffle(possible)
count = 0
while count < len(possible):
print(str(count+1) + ": " + possible[count])
count += 1
print("Please enter the number of your answer:")
Answ = input()
Answ = str(Answ)
while not Answ.isdigit():
print("That was not a number. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
Answ = int(Answ)
while Answ > 4 or Answ < 1:
print("That number doesn't correspond to any answer. Please enter the number of your answer:")
Answ = input()
Answ = int(Answ)
if possible[Answ-1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 1 * qaItem.diff
else:
print("Your answer was wrong.")
response = input("Would you want to try again? If so, input 'Yes' to attempt it again, if not just input whatever!")
if response == "Yes":
Answ = input("Which option would you go for this time?: ")
Answ = int(Answ)
if possible[Answ - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corr += 1
marks += 0.5 * qaItem.diff
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
else:
print("Correct answer was: " + qaItem.corrAnsw)
print("Explanation: " + qaItem.expl)
print("")
print("You answered " + str(corr) + " of " + str(len(qaList)) + " questions correctly.")
print("You have achieved a total score of " + str(marks) + ".")

即使有计时器,主线程也不能继续等待用户输入数字;因此,如果用户什么都不做,定时器函数就会运行,一旦它完成,主线程仍在等待的输入

print("Please enter the number of your answer:")
Answ = input() 

您可以有一个全局标志,计时器线程设置该标志来告诉主线程在计时器代码中将接收到的输入视为response1,还可以有一条标志来告诉计时器已接收到答案,等等,这很快就会变得相当复杂。

因此,与其试图通过定时器和主线程之间的通信来解决对input的阻塞调用,不如从https://stackoverflow.com/a/22085679/1527如果时间到了,就提前停止循环。

def timed_input(msg, timeout=10):
kb = KBHit()
print(msg)
end_time = time.time() + timeout
warn_time = 5
result = None
while True:
if kb.kbhit():
c = kb.getch()
if '0' <= c <= '9':
result = int(c)
break                
print(c)
if time.time() > end_time:
print('time is up')
break
if time.time() > end_time - warn_time:
print(f'{warn_time}s left')
warn_time = warn_time - 1
kb.set_normal_term()
return result

# Test    
if __name__ == "__main__":
result = timed_input('Enter a number between 1 and 4')
if result is None:
print('be quicker next time')
elif 1 <= result <= 4:
print('ok')
else: 
print(f'{result} is not between 1 and 4')

还要注意,分解成更小的函数有助于使代码更容易理解,测试的逻辑不需要知道超时的逻辑。

最新更新