0

I'm currently making a text-based strategy game with python, but I've come across a problem, I want to make the user receive 1 gold and lose 5 food every 10 seconds, so I made a loop:

import time

gold = 0
food = 100
while True:
    time.sleep(10)
    gold += 1
    food -= 5

But I can't run the main loop now because the program is stuck running the first one:

while True:
    what_to_do = input("What do you want to do?\n")
    if what_to_do == 'wood':
        wood()
    ...

I there any way I can constantly add gold and lose food at the same time as being able to play the game? Such as being able to run a loop in the background while the main loop runs, or am I just being stupid?

Golem
  • 1
  • 1
  • Does this answer your question? [What is the best way to repeatedly execute a function every x seconds in Python?](https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds-in-python) - You would probably want to look at any of the answers that mention they are not blocking. – wwii Mar 03 '20 at 18:31
  • While maybe overkill - you might want to run your game with [asyncio](https://docs.python.org/3/library/asyncio.html) - there will be a learning curve. Some of the answers in the previous link are Tornado solutions - Tornado uses an event loop similar to asyncio. ... [How can I periodically execute a function with asyncio?](https://stackoverflow.com/questions/37512182/how-can-i-periodically-execute-a-function-with-asyncio) – wwii Mar 03 '20 at 18:44
  • This is post useful, but the main problem is, I have to run a function, but i can't run the rest until that function is complete, and as the functions are usually infinite, this isn't very conveniant... – Golem Mar 03 '20 at 19:16

0 Answers0