以下是我正在制作的游戏的代码,在第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")
答案 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")