如何在不影响其余程序的情况下延迟程序的一部分?

时间:2019-12-19 15:33:55

标签: python loops time pygame delay

我有一个使用计分器的程序。该分数计数器最初为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

是否有一种方法可以独立于其余代码来运行分数减法?

3 个答案:

答案 0 :(得分:2)

您需要使用其他线程来计算分数。只需启动一个新线程即可降低分数。

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

答案 1 :(得分:1)

您需要以“运行到完成”的样式编写程序。

因此,给定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()函数中。

而且,它在单个线程中运行,因此不需要访问shipyscore的信号量。

答案 2 :(得分:1)

看看这个多线程程序。

  • 主程序显示“您可以在这里做其他事情”,然后等待您按Enter键
  • 另一个并行的功能是递增变量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 program\n")

def counter ():
    # Do an action in parallel
    global i
    while True:
        print("i =", i)
        i += 1
        time.sleep(1)

main_function()