from channels.generic.websocket import WebsocketConsumer from django.contrib.auth.models import User from games.models import GameModel import json queue_id: [int] = [] queue_ws: [WebsocketConsumer] = [] class MatchMaking(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.channel_name = "matchmaking" self.group_name = "matchmaking" def connect(self): user: User = self.scope["user"] if (user.is_anonymous or not user.is_authenticated): return self.channel_layer.group_add(self.group_name, self.channel_name) self.accept() global queue_id, queue_ws queue_id.append(user.pk) queue_ws.append(self) if len(set(queue_id)) == 2: game_id: int = GameModel().create(set(queue_id)) event = {"game_id": game_id} for ws in queue_ws: ws.send(text_data=json.dumps({'game_id': game_id})) queue_id.clear() queue_ws.clear() def disconnect(self, close_code): user: User = self.scope["user"] global queue_id, queue_ws if (user.pk in queue_id): queue_ws.pop(queue_id.index(user.pk)) queue_id.remove(user.pk) self.channel_layer.group_discard(self.group_name, self.channel_name)