自上次if语句运行以来的测量时间(Python)

时间:2018-02-03 12:12:36

标签: python-3.x oop pygame

我想让if语句只运行,如果它自上次运行以来超过x秒。我只是找不到那个。

3 个答案:

答案 0 :(得分:1)

您希望在time()模块中使用time方法。

import time

...
old_time = time.time()
...
while (this is your game loop, presumably):
  ...
  now = time.time()
  if old_time + x <= now:
    old_time = now
    # only runs once every x seconds.
...

答案 1 :(得分:1)

由于您没有提供任何代码,请留下这是您的计划:

while True:
    if doSomething:
        print("Did it!")

我们可以确保if语句只有在上次运行后的x秒内才会运行,执行以下操作:

from time import time

doSomething = 1
x = 1
timeLastDidSomething = time()

while True:
    if doSomething and time() - timeLastDidSomething > x:
        print("Did it!")
        timeLastDidSomething = time()

希望这有帮助!

答案 2 :(得分:0)

# Time in seconds
time_since_last_if = 30
time_if_ended = None
# Your loop
while your_condition:
    # You still havent gone in the if, so we can only relate on our first declaration of time_since_last_if 
    if time_if_ended is not None:
        time_since_last_if = time_if_ended - time.time()
    if your_condition and time_since_last_if >= 30:
        do_something()
        # defining time_if_ended to keep track of the next time we'll have the if available
        time_if_ended = time.time()