Search code examples
pythondjangogame-developmentdjango-channelsmatchmaking

How to use django channel to create a game lobby and matchmaking


I am using django channels to create a 2-player game like Tic Tac Toe or checkers.

My main issue is how I can preserve the state of the players that joined the lobby waiting to be paired. Would this be something I need to do in the connect method in the channel consumer? If not what if the approach here?


Solution

  • A websocket should be reactive to the information sent by a client rather than running loops that constantly check users or database entries. We need a new class in our consumers.py that implements the WebsocketConsumer class of course, but this is a 'QueueManager' websocket for managing our queue and dispatching the initial join command for our 'GameManager' websocket.

    Our player needs to begin by sending a message to the 'QueueManager' websocket. If the player has logged in, it sends a 'new join' command with its ID. If the game allows for guests, we generate the new ID on connect. If a game room is open or a player is waiting in a room, the 'QueueManager' websocket dispatches a command to 'join room integer'. When the player's code sees that, it sends a command to the 'GameManager' websocket telling it what room it is going to be joining.

    If no room is available, tell the user 'no room', then open a queue using a database model where each primary key is constant and the fields tell us how many users are in the queue. Each time you add to that queue, you create a different database model that has a unique database primary key whose value is equal to their place in the queue. When a player receives 'no room' send a command to the 'QueueManager' websocket 'checking room' for example every 10 seconds of time. When there is a new room open, the 'QueueManager' websocket dispatches the 'join room integer' command signal and moves all users forward one position in the queue by decrementing the total number of users in the database model with a constant primary key and going through all users database models with unique primary keys and updating their userID field to contain the next userID in the list. Remember that the unique primary keys of these database models are linked to the total number of users beginning with 0 or 1 that is saved in the database model which has a constant primary key that you can always access.