Home > Back-end >  how to make a variable's value added every time the stopwatch in python reached the multiple of
how to make a variable's value added every time the stopwatch in python reached the multiple of

Time:09-22

I'm using pygame to create a game with some monsters chasing the player. I want the monsters to increase their speed every 8 seconds. So, I make a stopwatch as a background task (so it would not interrupt the game code execution) with threading. So, I come with this code:

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()

If you notice the x variable, it's just an extra variable I added so the multiple_of_eight list would be infinite overtime until the while loop is breaked.

Now, what I expected the result would be is:

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...

Notice how the monster_speed variable is 1 more than the previous value. But actually, the result is:

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...

The monster_speed doesn't increase. That's why I need help so that the result is what I want.

CodePudding user response:

try this:

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()

CodePudding user response:

You could use the Timer class instead:

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()
    
  • Related