from channels.generic.websocket import WebsocketConsumer from django.contrib.auth.models import User from games.models import GameModel import json from .models import Waiter, WaitingRoom, WaitingRoomManager, normal 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.mode = int(self.scope['url_route']['kwargs']['mode']) self.group_name = self.mode waiting_room: WaitingRoom = normal.get(self.mode) waiting_room.append(Waiter(user.pk, self)) waiting_room.broadcast(f"{len(waiting_room)} / {waiting_room.mode}") if (len(waiting_room) == waiting_room.mode): game_id: int = GameModel().create(waiting_room.get_users_id()) waiting_room.broadcast("game_found", {"game_id": game_id}) waiting_room.clear() def disconnect(self, close_code): waiting_room: WaitingRoom = normal.get(self.mode) waiter: Waiter = waiting_room.get_member_by_socket(self) if (waiter is not None): waiting_room.remove(waiter)