如何在每次 python 中的秒表达到 8 的倍数(8、16、24、32 等...)时添加变量的值

how to make a variable's value added every time the stopwatch in python reached the multiple of 8 (8, 16, 24, 32, so on...)

我正在使用 pygame 创建一个有一些怪物追逐玩家的游戏。我希望怪物每 8 秒增加一次速度。因此,我使用线程将秒表作为后台任务(因此它不会中断游戏代码的执行)。所以,我来了这个代码:

from time import time, sleep
import threading

monsters_speed = 0.3
x = 0


# Time for monster to increase its speed
def time_speed():
    global monsters_speed, x
    start_time = time()
    while True:
        multiple_of_eight = list(range(8, x, 8))
        time_elapsed = round(time() - start_time)
        if multiple_of_eight.count(time_elapsed) > 0:
            monsters_speed += 1
        print(monsters_speed)
        print(time_elapsed)
        x += 1
        sleep(1)


time_speed_thread = threading.Thread(target=time_speed)

time_speed_thread.start()

如果您注意到 x 变量,它只是我添加的一个额外变量,因此 multiple_of_eight 列表将无限超时,直到 while 循环被中断。

现在,我预期的结果是:

0.3
0
0.3
1
0.3
2
0.3
3
0.3
4
0.3
5
0.3
6
0.3
7
0.3
8
1.3
9
and so on...

注意 monster_speed 变量如何比之前的值多 1。 但实际上,结果是:

0.3
0
0.3
1
0.3
2
0.3
3
0.3
4
0.3
5
0.3
6
0.3
7
0.3
8
0.3
9
and so on...

monster_speed没有增加。这就是为什么我需要帮助,这样结果才是我想要的。

您可以改用计时器 class:

monster_timer = None
monster_speed = 0
def increaseMonsterSpeed():
    global monster_speed, monster_timer
    monster_speed += 1
    monster_timer = threading.Timer(8, increaseMonsterSpeed)
    monster_timer.start()

# call the function once to start the speed increase process:
increaseMonsterSpeed()
    

试试这个:

from time import time, sleep
import threading

monsters_speed = 0.3

# Time for monster to increase its speed
def time_speed():
    global monsters_speed
    start_time = time()
    while True:
        time_elapsed = round(time() - start_time)
        ## you need to track the time_elapsed and check if it's can divided   
        ## by 8
        if time_elapsed%8 == 0 and not time_elapsed == 0:
            monsters_speed += 1
        print(monsters_speed)
        print(time_elapsed)
        sleep(1)


time_speed_thread = threading.Thread(target=time_speed)

time_speed_thread.start()