我必须在大学里用 Python 做一些练习。所以我需要构建一个问答游戏。要求是:
玩家必须在 20 秒内回答每个问题。如果玩家回答的时间超过 20 秒,即使他的回答正确,他也会得到 -1 分。
我刚刚尝试过threading
and Timer
。我的代码是这样的:
from time import *
import threading as th
score = 0
correct_answer = 1
def sctn():
global score
score -=1
print(score)
S = th.Timer(20.0, sctn)
S.start()
answer = int(input("enter : "))
if answer == correct_answer :
score += 1
else:
score -= 1
print(score)
S.cancel()
我为正确答案举了一个例子。但是当我运行代码时,如果我输入正确答案超过 20 秒,则得分 = -1 + 1 = 0,或者如果我输入错误答案超过 20 秒,得分 = -1 -1 = -2。
你的代码太多了。有两种情况:如果用户在20秒或更短的时间内输入了正确答案,则获得一分;否则他就会失去一个。
定时器函数不需要做任何事情。当您测试正确答案时,您还可以测试计时器是否已过期。 Timer是Thread的子类,因此它有一个功能is_alive
如果它仍在运行,则返回 True。
原始程序的问题在于,一旦计时器到期,答案就不再重要了。但无论如何你都会检查它,因此计时器函数中的 -1 点会添加到答案检查逻辑中的正或负 1 上。
from time import *
import threading as th
score = 0
correct_answer = 1
def sctn():
pass
S = th.Timer(20.0, sctn)
S.start()
answer = int(input("enter : "))
if answer == correct_answer and S.is_alive():
score += 1
else:
score -= 1
S.cancel()
print(score)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)