python - 随着时间的推移改变变量

标签 python variables time pygame seconds

我对Python有点陌生,我正在尝试在pygame中制作一个小游戏,其中我有一个“饥饿栏”,它会随着时间的推移而下降,我试图寻找一个模块或函数每隔 x 秒更改变量“饥饿”,但我发现的每个变量都会停止所有代码,直到时钟耗尽。任何人都知道我怎样才能让它发挥作用?

最佳答案

您处于使用 python 的 threading 模块的理想情况。 您可以生成一个在后台连续运行的子线程,并在指定的时间间隔后将 hunger 变量减少特定值。

例如:

import time
import threading

hunger = 100
def hungerstrike():
    global hunger
    while True:
        hunger -= 1
        time.sleep(2) # sleep for 2 seconds

def main():
    t = threading.Thread(target=hungerstrike) # start a child thread
    t.daemon = True
    t.start()

    # TODO: Do other work
    time.sleep(6)
    print("After 6 seconds, the value of hunger is:", hunger)

main()的输出:

After 6 seconds, the value of hunger is: 97

关于python - 随着时间的推移改变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60904063/

相关文章:

python - python 变量如何工作?

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

java - 获取应用程序关闭的时间。如何?

javascript - 将时间字符串 ("hours:minute") 转换为日期对象

javascript - 根据选定的小时和分钟从表格中获取下一个最接近的时间

python - 旋转后重命名列标题中的特殊字符

python - 使用 python selenium 从 HTML 页面中选择项目

python - pywinauto:遍历窗口中的所有控件

javascript - 是否可以使用变量来突出显示 jQuery 中的一行?

python - Flower Http Api 获取 Celery 任务详情