ft_transcendence/matchmaking/models.py

92 lines
2.0 KiB
Python

from django.db import models
from channels.generic.websocket import WebsocketConsumer
import json
# Create your models here.
class Waiter:
def __init__(self, user_id: int, socket: WebsocketConsumer):
self.user_id: int = user_id
self.socket: WebsocketConsumer = socket
def send(self, data: dict):
self.socket.send(text_data=json.dumps(data))
def accept(self):
self.socket.accept()
def disconnect(self):
self.socket.disconnect()
def __eq__(self, obj):
return self.user_id == obj.user_id
class WaitingRoom:
def __init__(self, waiting_room_manager, mode: int):
self._waiter_list: [Waiter] = []
self._mode: int = mode
self._waiting_room_manager = waiting_room_manager
def broadcast(self, data: dict):
for waiter in self._waiter_list:
waiter: Waiter
waiter.send(data)
def clear(self):
self._waiter_list.clear()
def get_waiter_by_socket(self, socket: WebsocketConsumer):
for waiter in self._waiter_list:
waiter: Waiter
if (waiter.socket is socket):
return waiter
return None
def append(self, waiter: Waiter):
self.remove(waiter)
waiter.accept()
self._waiter_list.append(waiter)
def remove(self, users_id):
for waiter in self._waiter_list:
waiter: Waiter = waiter
if (waiter == users_id):
waiter.disconnect()
if (self.empty()):
self._waiting_room_manager.remove(self)
return
def empty(self):
for _ in self._waiter_list:
return False
return True
def get_users_id(self):
return [waiter.user_id for waiter in self._waiter_list]
def __len__(self):
return len(self._waiter_list)
class WaitingRoomManager:
def __init__(self):
self._waiting_rooms: [WaitingRoom] = []
def get(self, mode: int):
for waiting_room in self._waiting_rooms:
waiting_room: WaitingRoom = waiting_room
if (waiting_room._mode == mode):
return waiting_room
tmp: WaitingRoom = WaitingRoom(self, mode)
self._waiting_rooms.append(tmp)
return tmp
def remove(self, waiting_room: WaitingRoom):
self._waiting_rooms.remove(waiting_room)
normal: WaitingRoomManager = WaitingRoomManager()