如何在达到设定时间后停止代码

How to stop code once a set time has been reached

我以前问过这个问题,但没有得到有效的答复。我希望玩家完成我的测验,但他们只有规定的时间来做,一旦达到规定的时间,游戏就会结束,不再问所有问题。

我尝试了多种不同的代码,但下面显示的是我正在尝试的最新代码。

import time

max_time = int(input('Enter the amount of seconds you want to run this: '))
start_time = time.time()  
while (time.time() - start_time) > max_time:
    sys.exit()

question_1 = ("Question?")
option_1 =(" a. 54 \n b. 50 \n c. 47 \n d. 38")
print(question_1)
print(option_1)    
answer_1 = input(">")        
if answer_1.lower() == "a":
    print("Correct")  
else:
    print("Incorrect") 

question_a2 = ("Question 2?")
option_a2 = (" a. 4 \n b. 6 \n c. 8 \n d. 10")
print(question_a2)
print(option_a2)            
answer_a2 = input(">")
if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")
end_time = time.time()

这段代码只是像往常一样不断地检查问题,没有任何反应。我是新手,如有任何帮助,我们将不胜感激。

首先,您应该开始使用函数来最大程度地减少代码重复(复制和粘贴)。一个简单但不是真正交互式的解决方案是在回答问题后检查时间。替换

if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")

if (time.time() - start_time) > max_time:
    print("Sorry, you didn't answer in time")
    stop_quiz = True
elif answer_1.lower() == "a":
    print("Correct")
    total_points += 1
else:
    print("Incorrect")

在问下一个问题之前,请检查 stop_quiz 是否为 True,只有在为 False 时才继续。我希望你明白了。我还引入了一个变量来计算正确回答的问题。

更新:使用 class 存储点数和时间重写了测验

import time

class Quiz:
  def __init__(self):
      self.total_points = 0
      self.stop_quiz = False
      self.start_time = time.time()
      self.max_time = int(input('Enter the amount of seconds you want to run this: '))

  def ask_question(self, question, options, correct_answer):
      if self.stop_quiz:
          return
      print(question)
      print(options)
      answer = input(">")
      if (time.time() - self.start_time) > self.max_time:
          print("Sorry, you didn't answer in time. The quiz is over")
          self.stop_quiz = True
      elif answer.lower() == correct_answer:
          print("Correct")
          self.total_points += 1
      else:
          print("Incorrect")

  def get_result(self):
      print("You got {} Points!".format(self.total_points))

quiz = Quiz()
quiz.ask_question("Question 1?", "a. 54 \nb. 50 \nc. 47 \nd. 38", "a")
quiz.ask_question("Question 2?", "a. 54 \nb. 20 \nc. 47 \nd. 38", "b")
quiz.get_result()