ft_transcendence/matchmaking/consumers.py

41 lines
1.2 KiB
Python
Raw Permalink Normal View History

2023-12-12 06:06:13 -05:00
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
2023-12-12 06:06:13 -05:00
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
2023-12-12 06:06:13 -05:00
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())
2023-12-23 10:56:04 -05:00
waiting_room.broadcast("game_found", {"game_id": game_id})
waiting_room.clear()
2023-12-12 06:06:13 -05:00
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, 1016)