我必须为高中项目创建这个基本游戏。我是python中的计时器的新手。我的代码如下:
import random
from threading import Timer
score = -1
directions = ["RIGHT", "LEFT", "UP", "DOWN"]
accdirection=random.choice(directions)
def timeOut():
out_of_time = "yes"
print("TESTING ")
while accdirection:
TimeLimit = 1
score = score + 1
accdirection=random.choice(directions)
print(accdirection)
out_of_time = "no"
t=Timer(TimeLimit,timeOut)
t.start()
fast = input()
if out_of_time == "yes":
accdirection = None
if accdirection in directions:
t.cancel()
if accdirection == "RIGHT":
if fast == "d":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "LEFT":
if fast == "a":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "UP":
if fast == "w":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
elif accdirection == "DOWN":
if fast == "s":
accdirection = random.choice(directions)
else:
accdirection = None
print("Oops, you clicked the wrong key.")
else:
print("Oof, too slow!")
accdirection = None
print("Your score is:", score)
代码的功能是python输出方向,然后用户必须输入w,a,s或d。如果他们得到了错误的密钥,游戏结束了,他们就输了。这部分工作正常。当时间用完时,它打印出“TESTING”,我只是为了测试它是否进入timeOut函数。但是,感觉out_of_time的值似乎总是保持不变:在这种情况下“不”。因此,accdirection的值无法重置为None以中断循环。如果大多数代码对我的问题毫无用处,我很抱歉。请告诉我如何解决这个问题。
你在out_of_time = "yes"
函数中设置timeOut
,但永远不会返回out_of_time
的更新值。
并且out_of_time
最初设置在全局命名空间中,因此请指出,并且您应该获得预期的行为:
def timeOut():
global out_of_time
out_of_time = "yes"
print("TESTING ")
return out_of_time