如何在不影响其余程序的情况下延迟程序的一部分? [英] How to delay a part of my program without affecting the rest?

查看:95
本文介绍了如何在不影响其余程序的情况下延迟程序的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何在不影响其余程序的情况下延迟程序的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆