由于我对堆栈溢出、Python和一般写作技巧的了解很差,我没有具体说明我使用的是pygame模块。我很抱歉我缺乏理解,并将致力于改进。。
大约2-3天前开始学习Python。最近,我的计时器实现遇到了一个问题。我使用的是time.sleep(10),但后来发现这实际上暂停了10秒的代码,而我需要它来计算10秒。我有办法做到这一点吗?在此之前,非常感谢您。
编辑:我现在知道“计时器”这个词可能不太合适。我实际上要做的是创造10秒的冷却时间。
发布于 2018-09-07 18:50:04
我认为您遇到的问题是您的代码是按顺序运行的。如果您希望在其他代码运行的同时运行一些代码(有点像在后台),您可以使用穿线。
import threading
import time
def in_thread():
print("Thread start")
time.sleep(10)
print("Thread end")
print("Start")
thread = threading.Thread(target=in_thread)
thread.start()
print("This continues")但是,如果您是作为一个冷却系统在游戏中这样做,我建议存储time.time(),这给当前的时间,以秒为单位,当行动第一次采取。当他们再次尝试执行此操作时,您可以将当前时间与存储时间进行比较,并查看它们是否传递了冷却时间(time.time() - startTime > 10:)。
发布于 2018-09-07 18:49:02
您可以使用threading.Timer设置定时器。
类threading.Timer 在指定的时间间隔过后执行函数的线程。
>>> import threading
>>> def hello():
... print("Hello")
...
>>> t =threading.Timer(5, hello)
>>> t.start()
Hellohttps://stackoverflow.com/questions/52228001
复制相似问题