我有一个使用计分器的程序.该分数计数器最初为100,并一直保持这种状态,直到超过某个阈值为止.阈值变量称为shipy,我的分数称为score.
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.
我实现了一种方法,一旦shipy超过400,我就会每0.1秒从我的分数中减去1,但是这样做会使我的整个程序运行速度变慢.
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.
下面是我的代码段:
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)然后在代码shipy > 400的某个位置调用t1.start().
Then just call t1.start() at some point in the code if shipy > 400.
更多推荐
如何在不影响其余程序的情况下延迟程序的一部分?
发布评论