我之前曾问过这个问题,但没有得到有效的答复。我希望玩家完成我的测验,但他们只有一定的时间来做,一旦达到设定的时间,游戏就会结束并停止询问所有问题。
我尝试了多种不同的代码,但是下面显示的是我正在尝试的最新代码。
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()
此代码仅继续处理正常问题,但没有任何反应。我还很新,任何帮助将不胜感激。
答案 0 :(得分:1)
首先,您应该开始使用函数来最大程度地减少代码重复(复制和粘贴)。一个简单但不是真正互动的解决方案是检查问题回答后的时间。替换
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,则仅继续。希望您能明白。我还引入了一个变量,用于计算正确的答案。
更新:使用用于存储点和时间的类重写测验
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()