Python游戏计时器

43 投票
10 回答
151590 浏览
提问于 2025-04-16 17:00

我想做一个简单的游戏,目标是在规定的时间内,比如10秒,尽可能多地收集方块。我该怎么做才能让计时器在程序开始时就开始计时,当它到达10秒时,执行某个操作(比如退出一个循环)呢?

10 个回答

7

我在我的Python程序中使用这个函数。这个函数的输入示例是:
value = time.time()

def stopWatch(value):
    '''From seconds to Days;Hours:Minutes;Seconds'''

    valueD = (((value/365)/24)/60)
    Days = int (valueD)

    valueH = (valueD-Days)*365
    Hours = int(valueH)

    valueM = (valueH - Hours)*24
    Minutes = int(valueM)

    valueS = (valueM - Minutes)*60
    Seconds = int(valueS)


    print Days,";",Hours,":",Minutes,";",Seconds




start = time.time() # What in other posts is described is

***your code HERE***

end = time.time()         
stopWatch(end-start) #Use then my code
10

使用 time.time() 或 datetime.datetime.now() 的时候,如果系统时间被更改了(比如用户手动改时间、通过网络时间同步服务(像 NTP)修正时间,或者在夏令时和标准时间之间切换),就会出现问题。

time.monotonic() 或 time.perf_counter() 似乎是更好的选择,但它们只在 Python 3.3 及以上版本可用。还有一种选择是使用 threading.Timer。至于这种方法是否比 time.time() 更可靠,这取决于它的内部实现。另外,要注意创建新线程在系统资源上并不是完全免费的,所以如果需要同时运行很多定时器,这可能不是个好主意。

53
import time

now = time.time()
future = now + 10
while time.time() < future:
    # do stuff
    pass

另外,如果你已经有了你的循环:

while True:
    if time.time() > future:
        break
    # do other stuff

这个方法在 pygame 中效果很好,因为它基本上要求你有一个大的主循环。

撰写回答