ft_transcendence/matchmaking/consumers.py

42 lines
1.2 KiB
Python

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))
print(len(waiting_room), "/", self.mode, [len(waiting_room),self.mode])
if (len(waiting_room) == self.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_waiter_by_socket(self)
if (waiter is not None):
waiting_room.remove(waiter)