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?

Red
  • 26,798
  • 7
  • 36
  • 58
  • I think what you're looking for is multi-threading. You can read about it [here](https://realpython.com/intro-to-python-threading) – Mayank Jan 06 '21 at 13:09

3 Answers3

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).

Red
  • 26,798
  • 7
  • 36
  • 58
limserhane
  • 1,022
  • 1
  • 6
  • 17
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")
Rethipher
  • 336
  • 1
  • 14
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
Red
  • 26,798
  • 7
  • 36
  • 58