Skip to content

Commit

Permalink
Merge pull request #49 from Nuno-Jesus/merge/front-master
Browse files Browse the repository at this point in the history
Merge 'merge/front-master' to master
  • Loading branch information
Nuno-Jesus authored Oct 23, 2024
2 parents 332cc79 + 4cc7697 commit c2a479e
Show file tree
Hide file tree
Showing 68 changed files with 4,167 additions and 1,203 deletions.
5 changes: 2 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
TOKEN_URL='https://api.intra.42.fr/oauth/token'
USER_INFO_URL='https://api.intra.42.fr/v2/me'
CLIENT_ID='u-s4t2ud-b82e9fe438563f339a906cd3bc30001cbb1785649c08b26fca0e4c1e2e7eddab'
CLIENT_SECRET='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'
REDIRECT_URI='http://localhost:8002/home42/'
CLIENT_SECRET='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'
POSTGRES_USER="anaraujo"
POSTGRES_PASSWORD="1234"
PGADMIN_DEFAULT_EMAIL="admin@email.com"
PGADMIN_DEFAULT_PASSWORD="1234"
PGADMIN_LISTEN_PORT="8080"
PGADMIN_LISTEN_PORT="8080"
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ clean:
backend/pong/__pycache__/ \
backend/pong/migrations/__pycache__/ \
backend/pong/templatetags/__pycache__/ \
backend/pong/migrations/*_initial.py
backend/pong/migrations/*_initial.py \
backend/pong/migrations/0*.py

mkdir data/

Expand Down
8 changes: 4 additions & 4 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ RUN apk add --update --no-cache python3-dev python3 py3-pip gcc musl-dev libpq-d
&& pip install "channels[daphne]" \
&& rm -rf /var/cache/apk/*




CMD source /.venv/bin/activate && python3 ./manage.py runserver 0.0.0.0:8002
CMD source /.venv/bin/activate \
&& python3 manage.py makemigrations \
&& python3 manage.py migrate \
&& python3 ./manage.py runserver 0.0.0.0:8002
1 change: 0 additions & 1 deletion backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
TOKEN_URL_A=os.getenv("TOKEN_URL")
CLIENT_ID_A=os.getenv("CLIENT_ID")
CLIENT_SECRET_A=os.getenv("CLIENT_SECRET")
REDIRECT_URI_A=os.getenv("REDIRECT_URI")
USER_INFO_URL_A=os.getenv("USER_INFO_URL")


Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
179 changes: 152 additions & 27 deletions backend/pong/consumers.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,170 @@
import json
from .views import game_create_helper, game_update_helper
from .models import TournamentsUsers, Users
from .serializers import TournamentsUsersSerializer, UsersSerializer
from icecream import ic

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.layers import get_channel_layer
import random


class TournamentConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = f'{self.scope["url_route"]["kwargs"]["tournament_id"]}'
self.user = self.scope["user"]
def connect(self):
self.room_group_name = f'{self.scope["url_route"]["kwargs"]["tournament_id"]}'

async_to_sync(self.channel_layer.group_add)(
self.room_group_name, self.channel_name
)
async_to_sync(self.channel_layer.group_add)(
self.room_group_name, self.channel_name
)

self.accept()
self.accept()

def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name, self.channel_name
)
return super().disconnect(code)
def receive(self, text_data):
tournament_id = self.room_group_name
all_tour_users = TournamentsUsers.objects.filter(tournament_id=tournament_id)
serializer = TournamentsUsersSerializer(all_tour_users, many=True)
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name, self.channel_name
)
return super().disconnect(code)
def receive(self, text_data):
tournament_id = self.room_group_name
all_tour_users = TournamentsUsers.objects.filter(tournament_id=tournament_id)
serializer = TournamentsUsersSerializer(all_tour_users, many=True)

tour_users_data = serializer.data
tour_users_data = serializer.data

for tour_user in tour_users_data:
user = Users.objects.get(pk=tour_user['user_id'])
user_data = UsersSerializer(user).data
tour_user['user'] = user_data
for tour_user in tour_users_data:
user = Users.objects.get(pk=tour_user['user_id'])
user_data = UsersSerializer(user).data
tour_user['user'] = user_data

async_to_sync(self.channel_layer.group_send)(
self.room_group_name, {"type": "send.users", "message": json.dumps(tour_users_data)}
)
async_to_sync(self.channel_layer.group_send)(
self.room_group_name, {"type": "send.users", "message": json.dumps(tour_users_data)}
)

def send_users(self, event):
self.send(text_data=event["message"])
def send_users(self, event):
self.send(text_data=event["message"])


class RemoteGameQueueConsumer(WebsocketConsumer):
queue = {}

def connect(self):
self.accept()
self.user = self.scope['user']
self.room_name = ''
self.game_id = 0

# if the queue is empty: (no room available)
# - create a new channel_name and add it to the object
# - push the new object alongside the channel name to the queue
# else: (available rooms)
# - Pop the first available room in the queue
# - Add the client to the room
# - Broadcast a message to the channel with a starting command
if self.user.id in self.queue:
return

if len(self.queue) == 0:
ic('adding player to queue')
self.add_player_to_queue()
else:
ic('adding player to waiting room')
self.add_player_to_waiting_room()
ic(self.queue)

def add_player_to_queue(self):
"""
This will add the new player to the queue and also create a channel group
(a 'waiting room') to allow another player to join in
"""
self.room_name = "room_%s" % self.user.id

self.queue[self.user.id] = {
'id': self.user.id,
'username': self.scope['user'].username,
'room_name': self.room_name
}
async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)

def add_player_to_waiting_room(self):
"""
Since the queue is not empty, this means there is already at least
1 waiting room. We add the current player to the waiting room and
send a START command to initiate the game. This also removes the
waiting room from the queue.
"""

host_id = list(self.queue.keys())[0]
host_player = self.queue[host_id]
self.room_name = host_player['room_name']
curr_player = {
'id': self.user.id,
'username': self.scope['user'].username,
'room_name': self.room_name
}

new_game_data = {
"user1_id": host_id,
"user2_id": self.user.id,
"type": "Remote"
}

new_game = json.loads(game_create_helper(new_game_data).content)
async_to_sync(self.channel_layer.group_add)(host_player['room_name'], self.channel_name)
async_to_sync(self.channel_layer.group_send)(
self.room_name, {
"type": "send.start.game.message",
"message": json.dumps({
'gameID': new_game['id'],
'player1': host_player,
'player2': curr_player,
'ball': {
'direction': {
'x': 1 if random.randint(0, 1) == 1 else -1,
'y': 1 if random.randint(0, 1) == 1 else -1
}
}
})
}
)
del self.queue[host_id]

def disconnect(self, code):
if self.user.id in self.queue:
del self.queue[self.user.id]
return super().disconnect(code)

def receive(self, text_data=None):
handlers = {
'UPDATE': 'send.update.paddle.message',
'SYNC': 'send.ball.sync.message',
'FINISH': 'send.end.game.message'
}
data = json.loads(text_data)
event = data['event']

if event == 'FINISH':
game_data = data['data']
game_id = game_data['id']
del game_data['id']
game_update_helper(data['data'], game_id)

async_to_sync(self.channel_layer.group_send)(
self.room_name, {
"type": handlers[event],
"message": text_data
}
)

def send_start_game_message(self, event):
self.send(event['message'])

def send_ball_sync_message(self, event):
self.send(event['message'])

def send_update_paddle_message(self, event):
self.send(event['message'])

def send_end_game_message(self, event):
self.send(event['message'])
6 changes: 5 additions & 1 deletion backend/pong/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.1.1 on 2024-10-03 17:50
# Generated by Django 5.1.2 on 2024-10-23 19:47

import django.db.models.deletion
from django.conf import settings
Expand Down Expand Up @@ -130,9 +130,13 @@ class Migration(migrations.Migration):
('nb_goals_scored', models.IntegerField(default=0)),
('nb_goals_suffered', models.IntegerField(default=0)),
('max_ball_speed', models.IntegerField(default=0)),
('date_max_ball_speed', models.DateTimeField(null=True)),
('max_rally_length', models.IntegerField(default=0)),
('date_max_rally_length', models.DateTimeField(null=True)),
('quickest_game', models.IntegerField(default=2147483647)),
('date_quickest_game', models.DateTimeField(null=True)),
('longest_game', models.IntegerField(default=0)),
('date_longest_game', models.DateTimeField(null=True)),
('num_first_goals', models.IntegerField(default=0)),
('remote_time_played', models.IntegerField(default=0)),
('local_time_played', models.IntegerField(default=0)),
Expand Down
4 changes: 4 additions & 0 deletions backend/pong/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,13 @@ class UserStats(models.Model):
nb_goals_scored = models.IntegerField(default=0)
nb_goals_suffered = models.IntegerField(default=0)
max_ball_speed = models.IntegerField(default=0)
date_max_ball_speed = models.DateTimeField(null=True)
max_rally_length = models.IntegerField(default=0)
date_max_rally_length = models.DateTimeField(null=True)
quickest_game = models.IntegerField(default=2147483647)
date_quickest_game = models.DateTimeField(null=True)
longest_game = models.IntegerField(default=0)
date_longest_game = models.DateTimeField(null=True)
num_first_goals = models.IntegerField(default=0)
remote_time_played = models.IntegerField(default=0)
local_time_played =models.IntegerField(default=0)
Expand Down
1 change: 0 additions & 1 deletion backend/pong/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ class Meta:
fields = ['id', 'type', 'status', 'description', 'user_id', 'other_user_id', 'created_at']

class GamesSerializer(serializers.ModelSerializer):

class Meta:
model = Games
fields = '__all__'
Expand Down
1 change: 0 additions & 1 deletion backend/pong/templates/navs.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
<script defer src="{% static 'js/suggest_users.js' %}"></script>
<script defer src="{% static 'js/friends.js' %}"></script>
<script defer src="{% static 'js/friend-block.js' %}"></script>
<script defer src="{% static 'js/edit-profile.js' %}"></script>
<script defer src="{% static 'js/notifications.js' %}"></script>

<main id="MainPage" style="padding: 70px;">
Expand Down
Loading

0 comments on commit c2a479e

Please sign in to comment.