python - How to decrease value of a variable with time -
here code game making, on lines 9-13 trying make hunger variable decrease every 180 seconds 10, not working.
import threading print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print(" welcome 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 , stamina >0 , hunger >0: if hunger <50: print("you hungry.") if stamina <10: print("you feeling exhausted.") if health <50: print("you unhealthy.") print("you dead")
- first, don't need pass value since pass copy. make variable global.
- then,
while
loop needs passive delay or you're looping 100% active cpu. - you have protect against concurrent access of
health
variable, usingthread.lock
- another problem: thread needs stop rearming or process doesn't exit. stop rearming thread when
health < 0
a minimal complete & verifiable & working example, timer set 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 , stamina >0 , hunger >0: lock.release() time.sleep(0.5) # cpu isn't 100% if hunger <50: print("you hungry.") if stamina <10: print("you feeling exhausted.") if health <50: print("you unhealthy.") lock.acquire() print("you dead")
Comments
Post a Comment