Skip to content

Commit

Permalink
Merge pull request #46 from bertt6/main
Browse files Browse the repository at this point in the history
prod updated
  • Loading branch information
berat-samli authored Apr 22, 2024
2 parents 709af42 + 1a46077 commit 5d25e7f
Show file tree
Hide file tree
Showing 32 changed files with 362 additions and 204 deletions.
2 changes: 1 addition & 1 deletion API/API/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
re_path(r'^ws/chat/(?P<room_name>[^/]+)/(?P<nickname>[^/]+)$', ChatConsumer.as_asgi()),
re_path(r'^ws/online/(?P<user_id>[^/]+)$', OnlineUsersConsumer.as_asgi()),
re_path(r'^ws/requests/(?P<nickname>[^/]+)$', RequestConsumer.as_asgi()),
re_path(r'^ws/match-making/(?P<nickname>[^/]+)$', MatchMakingConsumer.as_asgi()),
re_path(r'^ws/matchmaking/(?P<nickname>[^/]+)$', MatchMakingConsumer.as_asgi()),
re_path(r'^ws/game/(?P<game_id>[^/]+)$', GameConsumer.as_asgi()),
]

Expand Down
16 changes: 15 additions & 1 deletion API/API/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,21 @@
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
),
'DEFAULT_THROTTLE_CLASSES': [

'rest_framework.throttling.AnonRateThrottle',

'rest_framework.throttling.UserRateThrottle'

],
'DEFAULT_THROTTLE_RATES': {

'anon': '50/min',

'user': '100/min'

}
}


Expand Down
2 changes: 0 additions & 2 deletions API/Apps/Chat/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ class Meta:
fields = "__all__"

class RoomSerializer(serializers.ModelSerializer):
messages = MessageSerializer(read_only=True, many=True)

class Meta:
model = Room
fields = '__all__'
3 changes: 2 additions & 1 deletion API/Apps/Chat/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# chat/urls.py
from django.urls import path
from .views import start_chat
from .views import start_chat, get_messages

urlpatterns = [
path('start-chat', start_chat, name='start-chat'),
path('get-messages/<uuid:room_id>', get_messages, name='get-messages'),
]
21 changes: 18 additions & 3 deletions API/Apps/Chat/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
from django.contrib.auth.models import User
from django.db.models import Q
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from Apps.Chat.api.serializers import RoomSerializer
from Apps.Chat.models import Room
from Apps.Chat.api.serializers import RoomSerializer, MessageSerializer
from Apps.Chat.models import Room, Message
from Apps.Profile.models import Profile


Expand All @@ -25,4 +26,18 @@ def start_chat(request):
except Room.DoesNotExist:
room = Room.objects.create(first_user=request.user.profile, second_user=second_user)
room_serializer = RoomSerializer(room)
return Response({"success": True, "room": room_serializer.data}, status=200)
return Response({"success": True, "room": room_serializer.data}, status=200)


@api_view(["GET"])
@permission_classes([IsAuthenticated])
def get_messages(request, room_id):
try:
messages = Message.objects.filter(room=room_id)
paginator = PageNumberPagination()
paginator.page_size = 10
paginated_data = paginator.paginate_queryset(messages, request)
serializer = MessageSerializer(paginated_data, many=True)
return paginator.get_paginated_response({"success": True, "messages": serializer.data})
except Message.DoesNotExist:
return Response({"error": "Messages not found"}, status=404)
3 changes: 2 additions & 1 deletion API/Apps/Game/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ def add_player_in_que(player):

def remove_player_in_que(player):
all_keys = get_players_in_que()
all_keys.remove(player)
if player in all_keys:
all_keys.remove(player)
cache.set('players-in-que', json.dumps(all_keys))


Expand Down
20 changes: 13 additions & 7 deletions API/Apps/Game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@

class MatchMakingConsumer(WebsocketConsumer):
def connect(self):
self.profile = ProfileGetSerializer(
Profile.objects.get(nickname=self.scope['url_route']['kwargs']['nickname'])).data
self.accept()
self.profile = ProfileGetSerializer(Profile.objects.get(nickname=self.scope['url_route']['kwargs']['nickname'])).data
async_to_sync(self.channel_layer.group_add)(
'player-%s' % self.profile['nickname'],
'player-%s' %self.profile['nickname'],
self.channel_name
)
add_player_in_que(self.profile)
self.accept()
self.check_game()

def disconnect(self, close_code):
remove_player_in_que(self.profile)
Expand All @@ -38,9 +38,14 @@ def disconnect(self, close_code):
def match_making_message(self, event):
self.send(text_data=json.dumps({
'message': event['message'],
'game': event['game']
'game_id': event['game_id']
}))

def check_game(self):
players_in_que = get_players_in_que()

if len(players_in_que) == 2:
threading.Thread(target=self.match_making).start() # opening thread because socket time out while true

def match_making(self):
players = sorted(get_players_in_que(), key=lambda x: x['mmr'])
Expand All @@ -53,16 +58,17 @@ def match_making(self):
player2=Profile.objects.get(id=matched_players[1]['id']))
self.send(text_data=json.dumps({
'message': f'Match found! Ready for playing!',
'game': GameSerializer(game).data,
'game_id': GameSerializer(game).data['id'],
}))
async_to_sync(self.channel_layer.group_send)(
f'player-{matched_players[1]['nickname'] if self.profile['nickname'] == matched_players[0]['nickname'] else matched_players[0]['nickname']}',
{
"type": "match_making_message",
"message": 'Match found! Ready for playing!',
"game": GameSerializer(game).data,
"game_id": GameSerializer(game).data['id'],
}
)
players = sorted(get_players_in_que(), key=lambda x: x['mmr'])
break
time.sleep(0.1)
ideal_mmr += 0.5 # up to value and time intervals can be added
Expand Down
16 changes: 7 additions & 9 deletions API/Apps/Game/models.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
import uuid

from django.db import models

from django.apps import apps
from Apps.Profile.models import Profile
from Apps.Tournament.models import Tournament


# Create your models here.


class Game(models.Model):
id = models.UUIDField(primary_key=True,default=uuid.uuid4)
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
player1 = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='player1')
player2 = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='player2')
winner = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='winner', null=True, blank=True,default=None)
tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, blank=True, null=True)
winner = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='winner', null=True, blank=True,
default=None)
is_finished = models.BooleanField(default=False)
date = models.DateTimeField(auto_now_add=True)
tournament = models.ForeignKey('Tournament.Tournament', on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
return f'{self.player1} vs {self.player2} on {self.date} with Id {self.id}'

def save(self, *args, **kwargs):
if self.winner:
self.is_finished = True
super().save(*args, **kwargs)
super().save(*args, **kwargs)
Empty file.
3 changes: 3 additions & 0 deletions Backend/Apps/Matchmaking/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions Backend/Apps/Matchmaking/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class MatchmakingConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'Apps.Matchmaking'
Empty file.
3 changes: 3 additions & 0 deletions Backend/Apps/Matchmaking/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions Backend/Apps/Matchmaking/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
9 changes: 9 additions & 0 deletions Backend/Apps/Matchmaking/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@


from django.urls import path

from . import views

urlpatterns = [
path('', views.index, name='matchmaking'),
]
5 changes: 5 additions & 0 deletions Backend/Apps/Matchmaking/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.shortcuts import render


def index(request):
return render(request, 'Matchmaking/matchmaking.html')
3 changes: 2 additions & 1 deletion Backend/Backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
'Apps.Home.apps.HomeConfig',
"Apps.Profile.apps.ProfileConfig",
"Apps.SocialMedia.apps.SocialMediaConfig",
"Apps.Game.apps.GameConfig"
"Apps.Game.apps.GameConfig",
"Apps.Matchmaking.apps.MatchmakingConfig"
]

MIDDLEWARE = [
Expand Down
1 change: 1 addition & 0 deletions Backend/Backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@
path('profile/', include('Apps.Profile.urls')),
path('social/', include('Apps.SocialMedia.urls')),
path('game/', include('Apps.Game.urls')),
path('matchmaking/', include('Apps.Matchmaking.urls'))
]
Binary file added Backend/static/public/MultiCloud.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Backend/static/public/SingleCloud.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Backend/static/public/SocialCloud.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
Binary file added Backend/static/public/music.mp3
Binary file not shown.
3 changes: 2 additions & 1 deletion Backend/static/scripts/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ async function App()

App().catch((error) => {
console.error(error)
});
});

42 changes: 42 additions & 0 deletions Backend/static/scripts/matchmaking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {loadPage} from "./spa.js";

function handleText() {
const BASE_TEXT = "FINDING A MATCH";
const text = document.getElementById("matchmaking text");
console.log(text);
let textIndex = 0;
setInterval(() => {
text.innerText = BASE_TEXT + ".".repeat(textIndex % 3);
textIndex += 1;
}, 1000);
}
function handleTimer() {
const timer = document.getElementById("matchmaking-timer");
let time = 0;
setInterval(() => {
time += 1;
let minutes = Math.floor(time / 60);
let seconds = time % 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
timer.innerText = `${minutes}:${seconds}`;
}, 1000);
}
async function connectToSocket() {
const nickname = localStorage.getItem("activeUserNickname")
const socket = new WebSocket(`ws://localhost:8000/ws/matchmaking/${nickname}`);
socket.onopen = () => {
console.log("Successfully connected to the server");
}
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data)
loadPage(`/game/${data.game_id}`);
}
}
async function App() {
handleText();
handleTimer();
await connectToSocket();
}
App();
63 changes: 38 additions & 25 deletions Backend/static/scripts/spa.js
Original file line number Diff line number Diff line change
Expand Up @@ -417,34 +417,22 @@ const routes = new Map([
url: ['/home/'],
html: `
<div
class="background container-fluid position-relative"
class="container-fluid position-relative home-wrapper"
style="padding: 0"
>
<div class="main-buttons-wrapper">
<div class="play-wrapper">
<div
style="
display: flex;
align-items: center;
justify-content: center;
"
>
<h1>WELCOME TO PONG</h1>
</div>
<div class="button-wrapper">
<button class="play-button">LEADERBOARD</button>
<button class="play-button" id="multiplayer-button">
MULTIPLAYER
</button>
<button class="play-button">SINGLEPLAYER</button>
<pong-redirect href="/social/">
<button class="play-button">SOCIAL</button>
</pong-redirect>
</div>
</div>
</div>
<pong-redirect class="home-element menu-element" id="single-menu" href="/play/">
<h1>Singleplayer</h1>
</pong-redirect >
<pong-redirect class="home-element menu-element" id="multi-menu" href="/matchmaking/">
<h1>Multiplayer</h1>
</pong-redirect>
<pong-redirect class="home-element" id="tournament-menu" href="/tournaments/">
<h1>Tournament</h1>
</pong-redirect >
<pong-redirect class="home-element" id="social-menu" href="/social/">
<h1>Social</h1>
</pong-redirect >
</div>
`
}],
['verification', {
Expand Down Expand Up @@ -545,6 +533,25 @@ const routes = new Map([
</div>
</div>
`
}],
['matchmaking',{
auth_required: true,
url: ['/matchmaking/'],
html: `
<div
class="container-fluid position-relative matchmaking-wrapper"
style="padding: 0"
>
<div class="matchmaking-container">
<div class="matchmaking-text-wrapper">
<h1 id="matchmaking text">FINDING A MATCH</h1>
<button id="close-matchmaking">X</button>
</div>
<div><h1 id="matchmaking-timer">00:00</h1></div>
</div>
</div>
`

}]
]);
const routeToFile = [
Expand All @@ -555,6 +562,7 @@ const routeToFile = [
[['/home/'], 'home'],
[['/verification/'], 'verification'],
[[/game\/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})/], 'game'],
[['/matchmaking/'], 'matchmaking'],
]
const requiredScripts = [
'/static/components/Notification.js',
Expand Down Expand Up @@ -629,7 +637,12 @@ function findRouteFile(pathName) {

export function loadPage(fileName) {
let data = findRouteFile(fileName);
if(!data){
console.error("No route found for",fileName);
return;
}
const route = routes.get(data);

let isMatch = false;
if (Array.isArray(route.url)) {
isMatch = route.url.some(url => {
Expand Down
Loading

0 comments on commit 5d25e7f

Please sign in to comment.