From 15897631979a739c868c66ebf0bb8170f63b25bd Mon Sep 17 00:00:00 2001 From: starnakin Date: Thu, 18 Jan 2024 13:59:19 +0100 Subject: [PATCH] game: add: player can leave and join game --- frontend/static/js/api/game/Game.js | 8 ++++---- games/consumers.py | 3 ++- games/objects/Game.py | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/frontend/static/js/api/game/Game.js b/frontend/static/js/api/game/Game.js index 811a3d4..a839a20 100644 --- a/frontend/static/js/api/game/Game.js +++ b/frontend/static/js/api/game/Game.js @@ -56,7 +56,6 @@ class Game this.walls.forEach(wall => { wall.draw(ctx); }); - console.log(this.players) this.players.forEach(player => { player.draw(ctx); }); @@ -115,12 +114,11 @@ class Game { const user_id = player_data.user_id; - const index = this.players.find(player => player.id === user_id); + const index = this.players.indexOf(this.players.find(player => player.id === user_id)); if (index === -1) return - - this.players.slice(index, 1); + this.players.splice(index, 1); } _receive_paddle_position(data) @@ -143,6 +141,8 @@ class Game this._init_game(data) else if (data.detail === "player_join") this._receive_player_join(data) + else if (data.detail === "player_leave") + this._receive_player_leave(data) } _init_game(data) diff --git a/games/consumers.py b/games/consumers.py index 3c5971b..6ba0b6b 100644 --- a/games/consumers.py +++ b/games/consumers.py @@ -52,4 +52,5 @@ class GameWebSocket(WebsocketConsumer): self.member.receive(data) def disconnect(self, close_code): - self.game.remove(self.member) \ No newline at end of file + if (self.user.pk in self.game.players_id): + self.game.remove(self.member) \ No newline at end of file diff --git a/games/objects/Game.py b/games/objects/Game.py index 176224b..b62c90e 100644 --- a/games/objects/Game.py +++ b/games/objects/Game.py @@ -98,7 +98,7 @@ class Game(AbstractRoom): return player def _player_leave(self, player: Player): - # TODO send data to all players + self.broadcast("player_leave", player.to_dict(), [player]) self.players.remove(player) def _spectator_join(self, user_id: int, socket: WebsocketConsumer):