每次python中的秒表达到8的倍数(8、16、24、32等...)时,如何使变量的值相加
Posted
技术标签:
【中文标题】每次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...) 【发布时间】:2021-11-15 12:41:26 【问题描述】:我正在使用 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 没有增加。这就是为什么我需要帮助,这样才能得到我想要的结果。
【问题讨论】:
【参考方案1】:您可以改用 Timer 类:
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()
【讨论】:
【参考方案2】:试试这个:
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()
【讨论】:
哦,是的,我忘了你可以通过使用 '%' 而不是那个 multiply_of_eight 变量来检查它是否可以除以 8。 没问题@NNC21July以上是关于每次python中的秒表达到8的倍数(8、16、24、32等...)时,如何使变量的值相加的主要内容,如果未能解决你的问题,请参考以下文章