我对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/