【问题标题】:Change a variable over time随时间改变变量
【发布时间】:2020-07-09 06:12:09
【问题描述】:

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

【问题讨论】:

标签: python variables time pygame seconds


【解决方案1】:

您处于使用 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

【讨论】:

  • 您有任何网页或视频可以让我了解此代码的工作原理吗?或者你能解释一下吗?
  • @AbrahamEsquivelth 您可以在互联网(或 youtube)上搜索有很多关于使用 threading 模块的教程。对于初学者,您可以参考https://realpython.com/intro-to-python-threading/ 或者您可以查看官方 python 文档。
猜你喜欢
  • 2020-04-11
  • 2011-10-16
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2019-05-15
相关资源
最近更新 更多