fixed room post-connect message, added room migration init file

This commit is contained in:
Alexander Karpov 2022-06-26 18:04:09 +03:00
parent 355a6ed38c
commit 46344ad776
3 changed files with 71 additions and 23 deletions

View File

@ -206,21 +206,22 @@ class RoomConsumer(AsyncWebsocketConsumer):
if not await self.connect_to_room(): if not await self.connect_to_room():
await self.close() await self.close()
else:
await self.send(
json.dumps(
{
"type": "INFO",
"message": f"welcome to room {self.room_name}",
"opponent_score": self.scope["opponent_score"],
"opponent_deck": self.scope["opponent_deck"],
"opponent_online": self.scope["opponent_online"],
"first": self.scope["first"],
},
)
)
await self.channel_layer.group_send( # Join room group
self.room_group_name, await self.channel_layer.group_add(self.room_group_name, self.channel_name)
{
"type": "info",
"message": f"welcome to room {self.room_name}",
"opponent_score": self.scope["opponent_score"],
"opponent_deck": self.scope["opponent_deck_id"],
"opponent_online": self.scope["opponent_online"],
"first": self.scope["first"],
},
)
# Join room group
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
@sync_to_async @sync_to_async
def connect_to_room(self): def connect_to_room(self):
@ -236,7 +237,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
self.scope["room"] = room self.scope["room"] = room
# check if player can be in a room # check if player can be in a room
p_ids = [x.id for x in room.first().players.all()] p_ids = [x.player.id for x in room.first().players.all()]
if self.scope["player"] not in p_ids: if self.scope["player"] not in p_ids:
return False return False
@ -249,7 +250,6 @@ class RoomConsumer(AsyncWebsocketConsumer):
self.scope["deck"] = player.deck.id self.scope["deck"] = player.deck.id
p_ids.remove(player.player.id) p_ids.remove(player.player.id)
opponent = PlayerInRoom.objects.get(player_id=p_ids[0]) opponent = PlayerInRoom.objects.get(player_id=p_ids[0])
self.scope["opponent"] = opponent.player.id self.scope["opponent"] = opponent.player.id
@ -258,18 +258,20 @@ class RoomConsumer(AsyncWebsocketConsumer):
self.scope["opponent_first"] = opponent.first self.scope["opponent_first"] = opponent.first
self.scope["opponent_online"] = opponent.online self.scope["opponent_online"] = opponent.online
player.connected = True player.online = True
player.save(update_fields=["connected"]) player.save(update_fields=["online"])
return True return True
async def disconnect(self, close_code): async def disconnect(self, close_code):
# Leave room group # Leave room group
await self.channel_layer.group_discard(self.room_group_name, self.channel_name) await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
await self.disconnect_player()
@sync_to_async @sync_to_async
def disconnect_player(self): def disconnect_player(self):
self.scope["player_in_room"].connected = False if "player_in_room" in self.scope:
self.scope["player_in_room"].save(update_fields=["connected"]) self.scope["player_in_room"].online = False
self.scope["player_in_room"].save(update_fields=["online"])
# Receive message from WebSocket # Receive message from WebSocket
async def receive(self, text_data): async def receive(self, text_data):
@ -279,7 +281,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
{"type": "chat_message", "message": text_data}, {"type": "chat_message", "message": text_data},
) )
# info type message handler # info type group message handler
async def info(self, event): async def info(self, event):
message = event["message"] message = event["message"]
msg = {"type": "INFO", "message": message} msg = {"type": "INFO", "message": message}
@ -296,7 +298,7 @@ class RoomConsumer(AsyncWebsocketConsumer):
if "first" in event: if "first" in event:
msg["first"] = event["first"] msg["first"] = event["first"]
await self.send(text_data=json.dumps({"type": "INFO", "message": message})) await self.send(text_data=json.dumps(msg))
# Receive message from room group # Receive message from room group
async def chat_message(self, event): async def chat_message(self, event):

View File

@ -0,0 +1,46 @@
# Generated by Django 4.0.5 on 2022-06-23 22:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('game', '0002_deck_heroimageset_heroindeck_playerauthsession_and_more'),
]
operations = [
migrations.CreateModel(
name='Room',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.SlugField(max_length=16, unique=True)),
('created', models.DateTimeField(auto_now_add=True)),
('ended', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='PlayerInRoom',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first', models.BooleanField()),
('score', models.IntegerField()),
('deck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='decks', to='game.deck')),
('player', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='game.player')),
('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='players', to='room.room')),
],
),
migrations.CreateModel(
name='PlayerInQueue',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('channel_name', models.CharField(max_length=50)),
('score', models.IntegerField()),
('deck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='game.deck')),
('player', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='game.player')),
],
),
]

View File

@ -30,7 +30,7 @@ class PlayerInRoom(models.Model):
first = models.BooleanField() first = models.BooleanField()
score = models.IntegerField(blank=False) score = models.IntegerField(blank=False)
deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name="decks") deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name="decks")
connected = models.BooleanField(default=False) online = models.BooleanField(default=False)
def __str__(self): def __str__(self):
return f"{self.player.name} in room {self.room.slug}" return f"{self.player.name} in room {self.room.slug}"