我有一个程序,其中我使用分数计数器。该分数计数器最初是 100,并保持这种状态,直到超过某个阈值。阈值变量称为shipy
,我的分数称为score
。
一旦shipy
超过 400,我实现了一些东西,每 0.1 秒从我的分数中减去 1,但这样做会导致我的整个程序运行得更慢。
这是我的代码片段:
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
有没有办法独立于代码的其余部分运行分数减法?
您需要使用不同的线程来计算分数。只需开始一个新线程即可倒计时您的分数。
import threading
import time
def scoreCounter():
while shipy > 400:
time.sleep(0.1)
global score
score-=1
t1 = threading.Thread(target=scoreCounter)
然后,只需在代码中的某个点调用t1.start()
(如果shipy > 400
(。
看看这个多线程程序。
- 主程序打印"在这里你可以做其他事情",然后等待你按回车键
- 并行的另一个功能是递增变量
i
并打印它
我让你试试这个:
import threading
import time
def main_function():
global continuer_global, i
i = 0
t1 = threading.Thread(target = counter)
t1.daemon = True # With this parameter, the thread functions stops when you stop the main program
t1.start()
print("Here you can do other stuff")
input("Press Enter to exit programn")
def counter ():
# Do an action in parallel
global i
while True:
print("i =", i)
i += 1
time.sleep(1)
main_function()
您需要将程序设置为"运行完成"样式。
因此,给定一个以秒为单位返回当前时间的time_now()
函数,您可以编写如下代码:
prev_time = time_now()
while True:
run_program() # Your program runs and returns
curr_time = time_now()
if curr_time - prev_time >= 1:
prev_time += 1
if shipy > 400:
score -= 1
这样,您的代码在run_program()
就可以执行它必须执行的操作,但会尽快返回。上面的其余代码永远不会循环等待时间,而是只在应该运行时运行。
处理完score
后,您可以看到再次调用run_program()
。
这只是说明了原理。在实践中,您应该将shipy
检查合并到run_program()
函数中。
此外,这在单个线程中运行,因此无需信号量即可访问shipy
或score
。