我以前问过如何冷却,但我仍然是Python的初学者。有人能用一个例子来建议一个冷却的方法吗?我的意思是冷却,所以有人仍然可以使用命令,而其他的东西还在充电。一个例子是:
while True:
dummy=300
standopt=input("Choose between TWHV and SP (DUMMY MECHANIC UNFINISHED FOR SP).\nIf you already chose a Stand, you're choosing again due to the dummy's hospitalisation.")
if standopt=="TWHV" or standopt=="twhv" or standopt=="Twhv":
while True:
if dummy>=1:
Action = str(input("Your Stand awaits instructions...(e, r)"))
if Action=="e" or Action=="E":
print("Barrage (28)")
dummy=dummy-28
print("Your dummy is now on",dummy,"HP.")
elif Action=="r" or Action=="R":
print("Heavy Punch (30)")
dummy=dummy-30
print("Your dummy is now on",dummy,"HP.")我想要的是代码继续运行,但是有一种简单的方法,在计时器运行完之前将其中一个命令放到定时器上,然后可以再次使用,同时,还可以使用其他的操作。
发布于 2021-11-21 11:47:39
首先,我设置了两个函数来更新冷却时间和检查操作是否可用。我们将使用字典来存储每个动作的可用时间。
import time
cooldown = {}
def update(action, cool):
cooldown.update({action: time.time() + cool})
def validate(action):
return cooldown.get(action, 0) - time.time() <= 0您可以了解更多关于dict.get和dict.update方法的信息。
实现
我们会在打孔功能上试一试。
def punch():
if validate("punch"):
print("Heavy Punch.")
update("punch", cool=5)
else:
print("Cooling down.")游行示威
让我们同时打两拳,等6秒,然后再打一拳。前两拳同时进行,所以不允许你第二次打孔。但是,在等待了6秒之后,穿孔能力已经冷却了(冷却时间是5秒)。
punch()
punch()
time.sleep(6)
punch()它给出了以下结果。
Heavy Punch.
Cooling down.
Heavy Punch.完整代码
若要将其应用于您的用例,可以执行以下操作。
cooldown = {}
def update(action, cool):
cooldown.update({action: time.time() + cool})
def validate(action):
return cooldown.get(action, 0) - time.time() <= 0
while True:
dummy = 300
standopt = input("Choose between TWHV and SP (DUMMY MECHANIC"
"UNFINISHED FOR SP).\nIf you already chose a Stand, you're"
"choosing again due to the dummy's hospitalisation.")
if standopt.lower() == "twhv":
while True:
if dummy >= 1:
action = str(input("Your Stand awaits instructions...(e, r)"))
if validate(action):
if action.lower() == "e":
print("Barrage (28)")
dummy -= 28
print("Your dummy is now on", dummy, "HP.")
elif action.lower() == "r":
print("Heavy Punch (30)")
dummy -= 30
print("Your dummy is now on", dummy, "HP.")
update(action, cool=5)
else:
print("Cooling down.")https://stackoverflow.com/questions/70020738
复制相似问题