Ask coding questions

← Back to all posts
Stats won't decrease over time.
MatthewGilmour (0)

Basically I have three stats, hunger thirst and temperature. They are supposed to be decreased by 1 point every second, and can be shown by pressing 'e'. The problem is that they will only go down by one point to 99, then stop. I've tried as much as I can think of but to no avail. Any help would be much appreciated.

Answered by OldWizard209 (1357) [earned 5 cycles]
View Answer
Comments
hotnewtop
OldWizard209 (1357)

Here is my solution to the problem. Sorry about the time I took:

import time
from threading import Thread

hunger = 100
thirst = 100
temperature = 100
print("You've woken up after a plane crash. What you do and where you go is up to you. Just watch out for the elements.")

def decrease_stats():
    global hunger, thirst, temperature
    while True:
        time.sleep(1)
        hunger -= 1
        temperature -= 1
        thirst -= 1

Thread(target=decrease_stats).start()

while True:
    stat = input("Enter command: ")
    if stat == "e":
        print("Your hunger is:", hunger, "Your thirst is", thirst, "Your temperature is", temperature)

Using Threading is the only way you can actually decrease the stats while allowing the player to interact.

OldWizard209 (1357)

This is happening because you are defining a new variable to hunger, thirst, and temperature when subtracting one. Also because x is 0, which evaluated to False and is not great when using `while loops. So what you have to do is this:

while True: 
  time.sleep(1)
  hunger -= 1
  temperature -= 1
  thirst -= 1
  stat = readchar()
    
if stat == "e":
  print("Your hunger is:",hunger,"Your thirst is",thirst, "Your temperature is",temperature)

Also the last if statement should be outside the while Loop.

MatthewGilmour (0)

Thanks, this worked for the most part aside from the stats not displaying when 'e' is pressed, it only displays when it is inside the loop, however at that point it only decreases the values every time 'e' is pressed. If you have any more advice on that it would be very helpful.

OldWizard209 (1357)

I see. my code doesn't work. And that is because python interprets code line by line. To actually decrease the stats, while letting the user play the game, you will need to use the threading module to actually run the code that decreases the stats in the background, while the user plays the game. Sorry for the late reply. @MatthewGilmour