我回到编程上,所以我开始了一个项目,该项目根据用户输入的侧面数量以及用户希望掷出骰子的次数来掷骰子。我在程序中涉及时间的一部分遇到了麻烦。当提示用户在十秒钟内未输入用户信息时,我希望显示一条消息。如果在另外十秒钟内什么都没输入,则应显示一条消息,依此类推。我正在使用python。
目前大多数程序都在工作,但是只有在输入后才检查时间。因此,用户可以无限地坐在输入屏幕上,而不会得到提示。我真的迷住了如何同时等待输入,同时检查自从提示输入时起经过的时间。
def roll(x, y):
rvalues = []
while(y > 0):
y -= 1
rvalues.append(random.randint(1, x))
return rvalues
def waitingInput():
# used to track the time it takes for user to input
start = time.time()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
tElapsed = time.time() - start
if tElapsed <= 10:
tElapsed = time.time() - start
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))
waitingInput()
else:
print("I'm waiting...")
waitingInput()
任何建议将不胜感激。我正在努力改善编码,因此欢迎对无关代码进行建设性的批评。
答案 0 :(得分:0)
这种情况需要线程计时器类。 python标准库提供了一个:
import threading
...
def waitingInput():
# create and start the timer before asking for user input
timer = threading.Timer(10, print, ("I'm waiting...",))
timer.start()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
# once the user has provided input, stop the timer
timer.cancel()
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))