【问题标题】:How to delay a part of my program without affecting the rest?如何在不影响其余部分的情况下延迟我的程序的一部分?
【发布时间】:2020-04-12 05:32:10
【问题描述】:

我有一个使用计分器的程序。该分数计数器最初为 100 并保持不变,直到超过某个阈值。阈值变量称为shipy,我的分数称为score

一旦shipy 超过 400,我实现了每 0.1 秒从我的分数中减去 1 的东西,但是这样做会导致我的整个程序运行得更慢。

这是我的代码的 sn-p:

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

有没有办法独立于其余代码运行分数减法?

【问题讨论】:

  • “就在那个循环中”是什么意思?每当循环运行时,其他一切都不会。除非你有多个线程
  • 我不知道你的完整代码,但你可能必须使用多线程
  • 欢迎您!你能试着产生一个minimal reproducible example 吗?
  • 好的,所以每当这个循环运行时,其他一切都会停止。那么有什么方法可以在不停止其他所有操作的情况下做同样的事情吗?
  • @RandomPersonOnline 是的,看看我的回答。

标签: python loops time pygame delay


【解决方案1】:

您需要使用不同的线程来计算分数。只需启动一个新线程来计算您的分数。

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

【讨论】:

    【解决方案2】:

    看看这个多线程程序。

    • 主程序打印“Here you can do other things”,然后等待您按 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()
    

    【讨论】:

      【解决方案3】:

      您需要让您的程序采用“运行至完成”样式。

      因此,给定一个以秒为单位返回当前时间的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 不需要信号量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 2010-09-11
        • 2016-06-12
        相关资源
        最近更新 更多