Python 如果时间达到某一秒,如何设置条件添加一个对象

Python 如果时间达到某一秒,如何设置条件添加一个对象,python,pygame,Python,Pygame,我的情况有问题,如果秒数达到10,然后再添加一个食物对象,如下所示: if int(counting_seconds) == 10: numFood += 1 但不是只添加一个,而是不断增加食物的数量,我可能已经发现了问题,在计时器达到11之前还有几毫秒,但我不知道如何将我的条件更改为只添加1。这是我的计数秒以及毫秒和分钟: start_time = pygame.time.get_ticks() counting_time = pygame.time.get_ticks() - st

我的情况有问题,如果秒数达到10,然后再添加一个食物对象,如下所示:

if int(counting_seconds) == 10:
    numFood += 1
但不是只添加一个,而是不断增加食物的数量,我可能已经发现了问题,在计时器达到11之前还有几毫秒,但我不知道如何将我的条件更改为只添加1。这是我的计数秒以及毫秒和分钟:

start_time = pygame.time.get_ticks()
counting_time = pygame.time.get_ticks() - start_time
counting_millisecond = str(math.floor(counting_time%1000)).zfill(3)
counting_seconds = str(math.floor(counting_time%60000/1000)).zfill(2)
counting_minutes = str(math.floor(counting_time/60000)).zfill(2)

确保只更新一次的一种方法是设置一个bool,该bool仅在
计数秒数
不是10时重置:

added_food = False

...

if int(counting_seconds) == 10 and not added_food:
    numFood += 1
    added_food = True
elif int(counting_seconds) != 10:
    added_food = False

注意:
added\u food
变量需要在此范围之外声明,以便在每次迭代中不会重置为
False

您需要向我们显示完整的代码,它显示您调用
if
语句的频率。我的猜测是,这是一个每秒运行不止一次的紧密循环,因此它将增加
numFood
很多次。非常感谢!我从来没有想过要有一个布尔来决定你帮了大忙!