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
|
|
|
|
|
2023-12-23 06:54:33 -05:00
|
|
|
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)
|
|
|
|
|
2023-12-23 06:54:33 -05:00
|
|
|
self.mode = int(self.scope['url_route']['kwargs']['mode'])
|
|
|
|
self.group_name = self.mode
|
2023-12-12 06:06:13 -05:00
|
|
|
|
2023-12-23 06:54:33 -05:00
|
|
|
waiting_room: WaitingRoom = normal.get(self.mode)
|
|
|
|
waiting_room.append(Waiter(user.pk, self))
|
2023-12-12 06:06:13 -05:00
|
|
|
|
2023-12-23 06:54:33 -05:00
|
|
|
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())
|
2023-12-23 10:56:04 -05:00
|
|
|
waiting_room.broadcast("game_found", {"game_id": game_id})
|
2023-12-23 06:54:33 -05:00
|
|
|
waiting_room.clear()
|
2023-12-12 06:06:13 -05:00
|
|
|
|
|
|
|
def disconnect(self, close_code):
|
2023-12-23 06:54:33 -05:00
|
|
|
waiting_room: WaitingRoom = normal.get(self.mode)
|
|
|
|
waiter: Waiter = waiting_room.get_waiter_by_socket(self)
|
|
|
|
if (waiter is not None):
|
2023-12-23 10:47:22 -05:00
|
|
|
waiting_room.remove(waiter)
|