ft_transcendence/tournament/consumers.py

41 lines
1.2 KiB
Python
Raw Normal View History

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 TournamentWaitingRoom(WebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.channel_name = "tournament"
self.group_name = "tournament"
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.tournament_id = int(self.scope['url_route']['kwargs']['tournament_id'])
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({"detail": "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(self.scope["user"].pk)