疯狂的一分钟 - 如何在达到时间限制时使循环退出?
这段代码运行得不错……如果我把它完成了,但如果没完成就不行。我需要这个循环在时间到的时候就停止,就像标准考试一样,即使我还没答完所有题目。
The Mad Minute
[A] Randomly generate a bunch of different math questions
[B] User cannot continue a question until the correct answer has been made
[C] User have 60 seconds to solve 10 math problems
[D] Add 1 second to the final time for every wrong answer
import random
import time
OPERATORS = ["+", "-", "*"]
MIN_OPERAND = 3
MAX_OPERAND = 9
TOTAL_PROBLEMS = 5
def generateProblem():
left = random.randint(MIN_OPERAND, MAX_OPERAND)
right = random.randint(MIN_OPERAND, MAX_OPERAND)
operator = random.choice(OPERATORS)
expression = f"{left} {operator} {right}"
answer = eval(expression)
return expression, answer
incorrectAnswer = 0
input("Press enter to start!")
print("---------------------")
startTime = time.time()
loop = 0
while time.time() - startTime < 60 and loop < TOTAL_PROBLEMS:
for i in range(TOTAL_PROBLEMS):
expression, answer = generateProblem()
while True:
userInput = input("Problem #" + str(i + 1) + ": " + expression + " = ")
if userInput == str(answer):
loop += 1
break
incorrectAnswer += 1
print("Time's up!")
# Add any incorrect answer penalization to the total time
endTime = time.time()
totalTime = endTime - startTime
totalTime = "{:.2f}".format(totalTime)
finalTime = float(totalTime) + incorrectAnswer
print("---------------------")
print("You completed The Mad Minute in", totalTime, "seconds with", incorrectAnswer, "incorrect answers! Your final time is", finalTime)
我暂时把题目设置为5道,时间设置为5秒,因为为了测试30道题在60秒内回答实在太麻烦了。我把计时器也设置为5秒,以确保如果我在第一道题上呆太久,循环会停止,但实际上什么都没发生。我加了一个循环变量,希望它能在while循环中满足条件退出,但感觉是因为我回答得太慢被踢出了。
1 个回答
0
如果你不小心,你的循环可能会一直进行下去。把第一个while
语句去掉,改成下面这个,这样每个问题只允许回答错误5次,而且在处理循环的过程中也会检查时间,而不是在外面检查。
for i in range(TOTAL_PROBLEMS):
expression, answer = generateProblem()
incorrectAnswer = 0 # reset this for each question
while True:
userInput = input("Problem #" + str(i + 1) + ": " + expression + " = ")
if userInput == str(answer):
break
incorrectAnswer += 1
if incorrectAnswer > 5: # avoid infinite loop
print("Too many failed attempts ...")
break;
if time.time() - startTime >= 60: # check the elapsed time here
print("Time's up!")
break;