问题描述
我创建了一个数学问答游戏,可以向用户打印和方程式,例如 5 + 3 = ?,然后等待结果.如果答案正确,则用户赢,否则用户输.我想扩展游戏并添加一个功能,该功能将用户回答的时间限制为 3 秒,如果他不回答他就输了.
I have created a mathematical quiz game that prints and equation to the user like, 5 + 3 = ?, and waits for the result. If the answer is right the user wins if not the user loses. I want to extend the game and add a feature that places a time limit of 3 seconds for the user to answer, if he don't the he loses.
一开始我尝试使用 time 模块和 time.sleep() 函数,但这也延迟了整个程序的逻辑.
At the beggining I tried using the time module and the time.sleep() function but this also delayed the whole program's logic.
这是一个伪代码的想法:
Here is an idea with pseudo code:
if (answer = wrong || time = 0)
lost...
推荐答案
如果您想检查用户是否在回答时花费了很长时间,您可以使用 time
模块来计算差异:
if you want to check if the user took to long when he answered you can use the time
module to calculate the diffrence:
start_time = time.time()
show_question()
answer = get_answer()
end_time = time.time()
if (answer = wrong || end_time - start_time > 3)
lose()
如果您希望用户在 3 秒后松开(无需等待他们输入答案),则必须使用线程,如下所示:
if you want the user to loose when 3 seconds as passed (without waiting for them to input a answer) you will have to use threading, like this:
timer = threading.Timer(3, lose)
show_question()
answer = get_answer()
timer.cancel()
if (answer = wrong)
lose()
这篇关于实现与游戏逻辑并行运行的计时器(倒计时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!