add: matchmaking
This commit is contained in:
48
matchmaking/consumers.py
Normal file
48
matchmaking/consumers.py
Normal file
@ -0,0 +1,48 @@
|
||||
from channels.generic.websocket import WebsocketConsumer
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from games.models import GameModel
|
||||
|
||||
import json
|
||||
|
||||
queue_id: [int] = []
|
||||
queue_ws: [WebsocketConsumer] = []
|
||||
|
||||
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.accept()
|
||||
|
||||
global queue_id, queue_ws
|
||||
queue_id.append(user.pk)
|
||||
queue_ws.append(self)
|
||||
|
||||
if len(set(queue_id)) == 2:
|
||||
game_id: int = GameModel().create(set(queue_id))
|
||||
event = {"game_id": game_id}
|
||||
for ws in queue_ws:
|
||||
ws.send(text_data=json.dumps({'game_id': game_id}))
|
||||
queue_id.clear()
|
||||
queue_ws.clear()
|
||||
|
||||
|
||||
def disconnect(self, close_code):
|
||||
user: User = self.scope["user"]
|
||||
global queue_id, queue_ws
|
||||
if (user.pk in queue_id):
|
||||
queue_ws.pop(queue_id.index(user.pk))
|
||||
queue_id.remove(user.pk)
|
||||
self.channel_layer.group_discard(self.group_name, self.channel_name)
|
6
matchmaking/routing.py
Normal file
6
matchmaking/routing.py
Normal file
@ -0,0 +1,6 @@
|
||||
from django.urls import re_path
|
||||
from . import consumers
|
||||
|
||||
websocket_urlpatterns = [
|
||||
re_path(r'ws/matchmaking/', consumers.MatchMaking.as_asgi())
|
||||
]
|
Reference in New Issue
Block a user