2

I’m kind of new to python, I’m trying to make a little game in pygame, in which I have a “hunger bar” which go down over time, I was trying to look for a module or function that every x seconds change the variable “hunger” but each one that I have found stop all the code untill the clock runs out. Anyone has an idea of how can I get this to work ?

1 Answers1

3

You are in the ideal situation to use the python's threading module. You can spawn a child thread which runs continuously in background and decrement the hunger variable by certain value after the specified intervals.

For Example:

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)

Output of main():

After 6 seconds, the value of hunger is: 97
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
  • do you have any web page or video where I can learn how this code works? Or could you please explain me ? – Abraham Esquivel Mar 28 '20 at 18:08
  • @AbrahamEsquivelth You can search on internet (or youtube) there are lots of tutorials on using `threading` module. For starters you can refer `https://realpython.com/intro-to-python-threading/` or you can looks into official python docs. – Shubham Sharma Mar 29 '20 at 07:35