Phellipe Brasiliano
Phellipe Brasiliano

Reputation: 37

How to create parallel tasks in Python

I am creating a battle game for telegram groups as my beginner's project, one player challenges the other, and then a battle happens in the chat. Now I want to implement a "timeout" function for it. I've managed to make it work using _thread:

import _thread
class Battle:
    def __init__(self, chat_id):
        self.chat = chat
        print('Instance of battle started on chat %s' % self.chat)
        self.pcount = 0
        self.p1score = 0
        self.p2score = 0

    def reset(self):
        self.pcount = 0
        self.p1score = 0
        self.p2score = 0

def timeout(chat_id):
    time.sleep(90)
    battle = battledic[chat_id]
    if battledic[chat_id].timer == 1:
        sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
        battle.reset()
    else:
        return

battle = Battle(chat_id)
if message == "challenge":
    if battle.pcount == 0:
        _thread.start_new_thread(timeout, (chat_id,))
...

So basically what I'm doing is calling the timeout function, that is going to sleep in a different thread for 90 seconds, and then it checks if the battle still with only one player (pcount == 1), if it is the case, it sends the chat a message telling them the fight did not start, and then resets the battle instance.

The problem here is that I'm raising exceptions very often, even though it works fine most of the time, also sometimes it doesn't have the desired effect, closing ongoing battles. Researching I've found out that this is not the desired way of doing this butI could not find better solution, and maybe I want to run other battles from other chats in parallel too. What should be used in this case? cooperative multitasking? multiprocessing? the trheading module? thanks for any tips on this task!

Upvotes: 0

Views: 73

Answers (1)

cwahls
cwahls

Reputation: 753

I've got you started. I'm not sure how you are going to chat or keep record of who's playing.

My first thoughts were to run threads, but the while loop is easier.

# from threading import Thread
from time import sleep

no_one = True
battledic = {} # your dict here. It may be better to use a list of objects (classes) for your opponents

class Battle(object):
    def __init__(self, chat_id):
        self.chat_id = chat_id
        self.pcount = 0
        self.p1score = 0
        self.p2score = 0
        print('Instance of battle started on chat %s' % self.chat_id)

    def reset(self):
        self.pcount = 0
        self.p1score = 0
        self.p2score = 0

def wheres_waldo():
    x = 0; no_one = True
    while x < 90: # waits 90 seconds unless found
        for player in battledic.keys():
            if player.is_requesting: # found someone
                no_one = False
                break # quit looking
        else:
            print('No one yet')
        sleep(1); x+= 1
    if no_one:
        sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
        battle.reset()
    else:
        sendmessage(chat_id, 'Found someone')

def sendmessage(chat_id,message):
    print('%s on chat %s' % (message,chat_id))

battle = Battle(chat_id)
while True:
    message = raw_input('Command? ')
    if message == "challenge":
        if battle.pcount == 0:
            wheres_waldo()
            # first thoughts were to run threads but the while loop is easier
            # wait = Thread(target=timeout, args=(chat_id))
            # where = Thread(target=wheres_waldo)
            # wait.start();where.start()
            # wait.join();where.join()

Upvotes: 1

Related Questions