我有一个家庭作业要做,我真的需要一个解决方案。从昨天开始我一直在尝试这样做,但我不知道如何。
程序必须生成并打印一个字母或数字,然后用户必须尽快键入它并按 ENTER。30秒后游戏结束。
好吧,我不知道如何为游戏设置时间限制。我正在通过stackoverflow搜索,但没有发现任何有用的东西。请帮我。
**这是我到目前为止所做的。我尝试了 SYSS.STDER 答案中的代码,但它并不完全有效,因为当 30 秒结束时,游戏也应该结束,但是在这段代码中,当我输入最后一个字符时游戏结束了。
LOOP 不会停止,直到它完成并且我们发现我们已经过了最后期限。时间一到,就需要立即中断正在进行的任务。
max_time =30
start_time = time.time() # remember when we started
while (time.time() - start_time) < max_time:
response = "a" # the variable that will hold the user's response
c = "b" #the variable that will hold the character the user should type
score = 0
number = 0
c = random.choice(string.ascii_lowercase + string.digits)
print(c)
number = number + 1
response = input("Type a letter or a number: ") #get the user's response
if response == c and (time.time() - start_time) < max_time:
# if the response from the previous loop matches the character
# from the previous loop, increase the score.
score = score + 1