如何随时间减少变量的值

时间:2016-11-13 11:15:36

标签: python

以下是我正在制作的游戏的代码,在第9-13行,我试图让饥饿变量每180秒减少10次,但它不起作用。

import threading
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("           Welcome to my game")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

health = 100
stamina = 100
hunger = 100
def hungerdecrease(h):
    global hunger
    threading.Timer(180,hungerdecrease).start()
    h -= 10

hungerdecrease(hunger)

while  health > 0 and stamina >0 and hunger >0:
    if  hunger <50:
        print("You are hungry.")
    if  stamina <10:
        print("You are feeling exhausted.")
    if  health <50:
        print("You are unhealthy.")
print("You are dead")

1 个答案:

答案 0 :(得分:0)

  • 首先,由于您只是传递副本,因此无需传递该值。只需将变量设为全局。
  • 然后,您的while循环需要一些被动延迟,或者您使用100%活动CPU循环。
  • 您必须使用health
  • 防止对thread.Lock变量的并发访问
  • 另一个问题:线程需要停止重新安装或者进程不会退出。我在health < 0
  • 时停止重新安排线程

最小的完整&amp;可验证的工作示例,计时器设置为1:

import threading,time,sys

hunger = 100
stamina = 100
health = 100

lock = threading.Lock()

def hungerdecrease():
    global hunger
    if hunger > 0:
        # no rearm when dead
        threading.Timer(1,hungerdecrease).start()  # rearm timer
        lock.acquire()
        hunger -= 10
        lock.release()

threading.Timer(1,hungerdecrease).start()

lock.acquire()

while  health > 0 and stamina >0 and hunger >0:
    lock.release()
    time.sleep(0.5)  # so CPU isn't 100%
    if  hunger <50:
        print("You are hungry.")
    if  stamina <10:
        print("You are feeling exhausted.")
    if  health <50:
        print("You are unhealthy.")
    lock.acquire()
print("You are dead")