I have made a Cookie Clicker game on Python and am trying to get two functions to run in parallel while in an infinite loop.
I need them to be in parallel, since I want one of them to add one to a variable every second and the other one to add one to another variable every ten seconds. I do this by just using time.sleep()
, but if I use the same loop for both, it's just gonna run the first function, wait 1s then add one and then wait 10s and add another one.
Does anyone know a way around this?
def farm():
time.sleep(random.choice(range(1, 3)))`
x = 1
def automatic():
time.sleep(random.choice(range(1, 10)))
y = 1
while True:
farm()
automatic()
This is my code kinda simplified
I tried using two different threads from the threading library, but that started crashing.
CodePudding user response:
Instead of using threading, you can move your sleep outside of each function and check in each cycle if relevant function should trigger.
import time, random
def farm():
print("farm")
def automatic():
print("automatic")
next_farm = random.choice(range(1, 3))
next_automatic = random.choice(range(1, 10))
while True:
if next_farm > 0:
next_farm -= 1
else:
farm()
next_farm = random.choice(range(1, 3))
if next_automatic > 0:
next_automatic -= 1
else:
automatic()
next_automatic = random.choice(range(1, 10))
time.sleep(1)
CodePudding user response:
It depends on what framework you're using to make the game. I'm assuming you're using PyGame (because of the infinite loop), which is incompatible with multithreading. I recommend you keep track of the last event trigger, such as when automatic
and farm
were called using the time
or datetime
modules, and call them when e.g. 1s or 10s has elapsed by checking with an if statement.
CodePudding user response:
If you need to run both functions in parallel you can do this:
from threading import Thread
def func1():
print('Working')
def func2():
print("Working")
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
CodePudding user response:
Working with threads will fix your problem:
def farm():
x = 0
while True:
time.sleep(random.choice(range(1, 3)))
x = 1
print('Thread 1 value is: ' str(x))
def automatic():
y = 0
while True:
time.sleep(random.choice(range(1, 10)))
y = 1
print('Thread 2 value is: ' str(y))
e = threading.Event()
t1 = threading.Thread(target=farm)
t1.start()
t2 = threading.Thread(target=automatic)
t2.start()