【发布时间】:2022-12-03 12:49:06
【问题描述】:
我想知道如何在 python 中制作一个输入最多 5 秒的程序(例如,他可以在 2 秒后发送输入)我决定做一个简单的游戏,你基本上必须在 5 秒以下重写一个单词。我知道如何创建输入并让它等待 EXACTLY 5 秒,但我想要实现的是将最大输入时间设置为 5 秒,这样如果用户在让我们说 2 秒后键入答案,他将进入下一个单词。你能告诉我实现目标的方法吗?提前致谢!
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
# User gets maximum of 5 seconds to write the word,
# if he does it before 5 seconds pass ,he goes to next word (does not have to wait exactly 5 seconds, he
# can send input in e.g 2 seconds)
# if he does not do it in 5 seconds he loses game and it is finished
user_input = input(f"Type word '{word}': ")
#IF the word is correct go to next iteration
if(user_input==word):
continue
#If the word is incorrect finish the game
else:
print("You lost")
break
我试着用 threading.Timer() 来做,但它不起作用
import threading
class NoTime(Exception):
pass
def count_time():
raise NoTime
for word in ["banana","earth","turtle","manchester","coctail","chicken"]:
try:
#Create timer which raises exception after 5 seconds
timer = threading.Timer(5,count_time)
timer.start()
user_input = input(f"Type word '{word}': ")
#if timer hasn't lasted 5 seconds then destroy it in order to prevent unwanted exception
timer.cancel()
if user_input==word:
print("Correct")
else:
print("Incorrect, you LOSE!")
break
except NoTime:
print("You run out of time, you lose")
break
我得到的错误
Traceback (most recent call last):
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\papit\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1394, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\papit\OneDrive\Pulpit\Programming\Python Bro Course\Math\second\threading_training.py", line 7, in count_time
raise NoTime
NoTime
【问题讨论】:
标签: python python-3.x