如果时间达到某一秒,如何调节添加一个对象

问题描述

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

if int(counting_seconds) == 10:
    numFood += 1

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

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)

解决方法

确保只更新一次的一种方法是拥有一个仅在 counting_seconds 不是 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_food 变量需要在此范围之外声明,以免在每次迭代中都重置为 False