I have a program in which I utilize a score counter. That score counter is initially 100 and stays like that until a certain threshold is crossed. The threshold variable is called shipy
and my score is called score
.
I implemented something that subtracts 1 from my score every 0.1s once shipy
is over 400, but doing it like that causes my whole program to run slower.
Here a snippet of my code:
shipy = 0
score = 100
# some code here doing something, eg. counting shipy up
if shipy > 400:
time.sleep(0.1)
global score
score-=1
# more code doing something else
Is there a way to run that score subtraction independently of the rest of the code?
You need to use a different thread for your score calculation. Just start a new thread for counting down your score.
import threading
import time
def scoreCounter():
while shipy > 400:
time.sleep(0.1)
global score
score-=1
t1 = threading.Thread(target=scoreCounter)
Then just call t1.start()
at some point in the code if shipy > 400
.