2

I'm attempting to make a script that keeps the times of each boss in a game through text.

an example would be:

if line == 'boss1 down':
    print('boss1 timer set for 10 seconds')
    time.sleep(10)
    print("boss1 due")

if line == 'boss2 down':
    print('boss2 timer set for 15 seconds')
    time.sleep(15)
    print("boss2 due")

However, the clear issue is that only one boss can be timed at a time. Is there a function I can use that won't disrupt the code and allow me to time multiple at a given time?

1
  • I think what you're looking for is multi-threading. You can read about it here Commented Jan 6, 2021 at 13:09

3 Answers 3

1

You can use the Thread class from the built-in threading module:

from threading import Thread
import time

def timer(num, secs, line):
    if line == f'boss{num} down':
        print(f'boss{num} timer set for {secs} seconds ')
        time.sleep(secs)
        print(f"boss{num} due")

boss1 = Thread(target=timer, args=(1, 10, "boss1 down"))
boss2 = Thread(target=timer, args=(2, 15, "boss2 down"))

boss1.start()
boss2.start()

Output:

boss1 timer set for 10 seconds boss2 timer set for 15 seconds

boss1 due
boss2 due
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Asynchronous function :

import asyncio

async def boss1_down():
    print('boss1 timer set for 10 seconds')
    await asyncio.sleep(10)
    print("boss1 due")
asyncio.run(boss1_down())

, add arguments to the function for timers and boss.

As @Mayank mentioned, you can also use threads, which are a bit more complex to settle but you can control them (you cannot stop or wait an async function).

Comments

1

From this answer

You can use threading to do asynchronous tasks.

from threading import Thread
from time import sleep

def threaded_function(line):
    if line == 'boss1 down':
        print('boss1 timer set for 10 seconds')
        time.sleep(10)
        print("boss1 due")
    if line == 'boss2 down':
         print('boss2 timer set for 15 seconds')
         time.sleep(15)
         print("boss2 due")

if __name__ == "__main__":
    thread1 = Thread(target = threaded_function, args= 'boss1 down')
    thread1.start()
    thread1.join()

    thread2 = Thread(target = threaded_function, args= 'boss2 down')
    thread2.start()
    thread2.join()
    print("thread finished...exiting")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.