From 7b3f6b717923919ec1d7dbea64653ee68f62caa0 Mon Sep 17 00:00:00 2001 From: Enes Date: Mon, 15 Apr 2024 19:33:57 +0300 Subject: [PATCH 1/2] Fix styling issues and update URLs in templates and views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: temasictfic Co-authored-by: Aktaş --- indianpong/indianpong/settings.py | 2 ++ indianpong/pong/consumer_chat.py | 11 +++------- indianpong/pong/consumer_pong.py | 29 +++++++++++++------------- indianpong/pong/models.py | 3 ++- indianpong/pong/templates/base.html | 21 +++++++++++++++++++ indianpong/pong/templates/play-ai.html | 5 ----- indianpong/pong/views.py | 7 +++---- indianpong/static/js/chat.js | 10 ++++----- indianpong/static/js/game/play-ai.js | 8 +++---- indianpong/static/js/signup.js | 19 ----------------- 10 files changed, 55 insertions(+), 60 deletions(-) diff --git a/indianpong/indianpong/settings.py b/indianpong/indianpong/settings.py index 10b3be1..b944cbf 100644 --- a/indianpong/indianpong/settings.py +++ b/indianpong/indianpong/settings.py @@ -27,6 +27,8 @@ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = environ.get("DEBUG", default=True) +BASE_URL = environ.get("BASE_URL", default="http://localhost:8000") + ALLOWED_HOSTS = ['indianpong.com','indianpong.onrender.com', 'http://127.0.0.1:8000', 'localhost', '127.0.0.1']#environ.get("ALLOWED_HOSTS", default="").split(" ") CSRF_TRUSTED_ORIGINS = [ diff --git a/indianpong/pong/consumer_chat.py b/indianpong/pong/consumer_chat.py index 0ece607..c306f30 100644 --- a/indianpong/pong/consumer_chat.py +++ b/indianpong/pong/consumer_chat.py @@ -56,15 +56,12 @@ async def receive(self, text_data): accepter = await UserProfile.objects.aget(username=self.user.username) # create game object game = await Game.objects.acreate(group_name=group_name, player1=accepted, player2=accepter) - message = f"/remote-game/invite/{game.id}" #? Maybe do these in client side - m = await Message.objects.acreate(content=message, user=accepted, room_id=self.room_name) #? await self.channel_layer.group_send( self.room_group_name, { "type": "accept.game", - "message": message, + "game_id": game.id, "user": accepted.username, - "created_date": m.get_short_date(), #? blocking? } ) @@ -131,15 +128,13 @@ async def invite_game(self, event): })) async def accept_game(self, event): - message = event["message"] + game_id = event["game_id"] user = event["user"] - created_date = event["created_date"] # Send message to WebSocket await self.send(text_data=json.dumps({ "type": "accept.game", - "message": message, + "game_id": game_id, "user": user, - "created_date": created_date, })) async def decline_game(self, event): diff --git a/indianpong/pong/consumer_pong.py b/indianpong/pong/consumer_pong.py index a0b4c31..fad57ec 100644 --- a/indianpong/pong/consumer_pong.py +++ b/indianpong/pong/consumer_pong.py @@ -192,7 +192,6 @@ async def receive(self, text_data): await self.end_handler(game_id, game) game.no_more = True - elif action == "paddle": #? Needs validation # Make a move in a game game_id = data["game_id"] @@ -586,25 +585,27 @@ def match_details(self): tournament_id = game.tournament_id return game_id, player1, player2, group_name, tournament_id + @database_sync_to_async def record_stats_elo_wallet(self, game_id, winner_score, loser_score, winner, loser, game_duration): from .models import Game, UserProfile from .update import update_wallet_elo, update_stats_pong, update_tournament game = Game.objects.get(id=game_id) - game.winner_score = winner_score - game.loser_score = loser_score - game.winner =UserProfile.objects.get(username=winner) - game.loser = UserProfile.objects.get(username=loser) - game.game_duration = datetime.timedelta(seconds=game_duration) - game.save() - - update_wallet_elo(game.winner, game.loser) - update_stats_pong(game.winner, game.loser, winner_score, loser_score, game_duration, "remote") - - # İf the game is a tournament game - if game.tournament_id: #? Check - update_tournament(game) + if game.winner == None: + game.winner_score = winner_score + game.loser_score = loser_score + game.winner =UserProfile.objects.get(username=winner) + game.loser = UserProfile.objects.get(username=loser) + game.game_duration = datetime.timedelta(seconds=game_duration) + game.save() + + update_wallet_elo(game.winner, game.loser) + update_stats_pong(game.winner, game.loser, winner_score, loser_score, game_duration, "remote") + + # İf the game is a tournament game + if game.tournament_id: #? Check + update_tournament(game) async def record_for_disconnected(self, game_id, game): diff --git a/indianpong/pong/models.py b/indianpong/pong/models.py index 3374d9c..e45d6d7 100644 --- a/indianpong/pong/models.py +++ b/indianpong/pong/models.py @@ -13,6 +13,7 @@ from .utils import create_random_svg, get_upload_to from indianpong.settings import EMAIL_HOST_USER, STATICFILES_DIRS from django.utils import timezone +from django.conf import settings import uuid from datetime import timedelta from .game import MAX_SCORE @@ -365,7 +366,7 @@ def message_for_match(self, game): except Room.DoesNotExist: room = Room.objects.create(first_user=game.player1, second_user=game.player2) # Create message for the room with game link - message = f"http://localhost:8000/remote-game/tournament/{game.id}" + message = f"{settings.BASE_URL}/remote-game/tournament/{game.id}" Message.objects.create(user=game.player1, room=room, content=message) diff --git a/indianpong/pong/templates/base.html b/indianpong/pong/templates/base.html index 72bb3d6..c8fa5c8 100644 --- a/indianpong/pong/templates/base.html +++ b/indianpong/pong/templates/base.html @@ -123,6 +123,27 @@

{{context.baseInfoSubHeaderText3}}

return cookieValue ? cookieValue.pop() : ''; } + + + function showToast(content, status, iconClass) { + const liveToast = document.getElementById('liveToast'); + var toastContent = document.querySelector('#liveToast .fw-semibold'); + var toastIcon = document.querySelector('.toast-body .i-class i'); + + + toastIcon.className = iconClass; + liveToast.classList.remove('text-bg-danger'); + liveToast.className = 'toast'; + liveToast.classList.add(status); + + toastContent.textContent = content; + const toast = new bootstrap.Toast(liveToast); + toast.show(); + setTimeout(function() { + toast.hide(); + }, 8000); + } + diff --git a/indianpong/pong/templates/play-ai.html b/indianpong/pong/templates/play-ai.html index 99a0e49..c859b7c 100644 --- a/indianpong/pong/templates/play-ai.html +++ b/indianpong/pong/templates/play-ai.html @@ -21,11 +21,6 @@ -
- - 200 - -
diff --git a/indianpong/pong/views.py b/indianpong/pong/views.py index deea949..ddb6d38 100644 --- a/indianpong/pong/views.py +++ b/indianpong/pong/views.py @@ -8,9 +8,8 @@ from django.http import HttpResponse, HttpResponseBadRequest from django.http import HttpResponseRedirect from django.http import Http404 +from django.conf import settings from django.utils import timezone -from django.core import serializers -from django.template import loader from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger import ssl @@ -126,7 +125,7 @@ def auth(request): auth_url = "https://api.intra.42.fr/oauth/authorize" fields = { "client_id": "u-s4t2ud-4b7a045a7cc7dd977eeafae807bd4947670f273cb30e1dd674f6bfa490ba6c45", # environ.get("FT_CLIENT_ID"), - "redirect_uri": "http://localhost:8000/auth_callback", # This should be parameterized + "redirect_uri": f"{settings.BASE_URL}/auth_callback", # This should be parameterized "scope": "public", # "state": state_req, # This will generate a 50-character long random string "response_type": "code", @@ -153,7 +152,7 @@ def auth_callback(request): "client_id": "u-s4t2ud-4b7a045a7cc7dd977eeafae807bd4947670f273cb30e1dd674f6bfa490ba6c45", # environ.get("FT_CLIENT_ID"), "client_secret": "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", # environ.get("FT_CLIENT_SECRET"), "code": code, - "redirect_uri": "http://localhost:8000/auth_callback", + "redirect_uri": f"{settings.BASE_URL}/auth_callback", } encoded_data = urllib.parse.urlencode(data).encode("utf-8") req = urllib.request.Request( diff --git a/indianpong/static/js/chat.js b/indianpong/static/js/chat.js index 2fae489..1e043af 100644 --- a/indianpong/static/js/chat.js +++ b/indianpong/static/js/chat.js @@ -159,7 +159,7 @@ const langMessages = { conversation.scrollTop = conversation.scrollHeight; }, 0); break; - case 'invite': + case 'invite.game': if (user === data.inviter) { showToast(`${langMessages[lang]['inviteyou']}`, 'text-bg-info', 'bi bi-bug-fill'); } else { @@ -168,7 +168,7 @@ const langMessages = { declineButton.style.display = 'block'; } break; - case 'accept': + case 'accept.game': if (user === data.accepted) { showToast(`${langMessages[lang]['acceptyou']}`, 'text-bg-success', 'bi bi-bug-fill'); } else { @@ -179,7 +179,7 @@ const langMessages = { swapApp(`/remote-game/invite/${data.game_id}`); break; - case 'decline': + case 'decline.game': if (user === data.declined) { showToast(`${langMessages[lang]['declineyou']}`, 'text-bg-success', 'bi bi-bug-fill'); } else { @@ -246,9 +246,9 @@ const langMessages = { } inviteButton.onclick = function (e) { - console.log("invite button clicked"); + //console.log("invite button clicked"); chatsocket.send(JSON.stringify({ - "action": "invite", + "action": "invite.game", "inviter": user, "invited": userNameOnChat, })) diff --git a/indianpong/static/js/game/play-ai.js b/indianpong/static/js/game/play-ai.js index cfd13a2..e4f1526 100644 --- a/indianpong/static/js/game/play-ai.js +++ b/indianpong/static/js/game/play-ai.js @@ -8,7 +8,7 @@ var start_time; var score1 = 0; var score2 = 0; -const MAX_SCORE = 10; +const MAX_SCORE = 3; // Player Abilities var likeaCheaterCount = 0; @@ -521,14 +521,14 @@ document.addEventListener("keyup", function(event) { // Ai Player -let reactionDelaySlider = document.getElementById('reactionDelay'); +/* let reactionDelaySlider = document.getElementById('reactionDelay'); let delayValueSpan = document.getElementById('delayValue'); reactionDelaySlider.oninput = function() { reactionDelay = this.value / ball.speed; delayValueSpan.innerText = Math.round(reactionDelay); // Display the current value of the slider let value = (this.value-this.min)/(this.max-this.min)*100 -} -let reactionDelay = Math.round(reactionDelaySlider.value / ball.speed); +} */ +let reactionDelay = 1000/(ball.speed*2)//Math.round(reactionDelaySlider.value / ball.speed); let lastBallPosition = { x: ball.x, y: ball.y }; let ballDirection = { x: 0, y: 0 }; let predictedY = paddle2.y; diff --git a/indianpong/static/js/signup.js b/indianpong/static/js/signup.js index 657caf8..e4cd3c3 100644 --- a/indianpong/static/js/signup.js +++ b/indianpong/static/js/signup.js @@ -71,25 +71,6 @@ export function initializeSignup() { } } -function showToast(content, status, iconClass) { - const liveToast = document.getElementById('liveToast'); - var toastContent = document.querySelector('#liveToast .fw-semibold'); - var toastIcon = document.querySelector('.toast-body .i-class i'); - - - toastIcon.className = iconClass; - liveToast.classList.remove('text-bg-danger'); - liveToast.className = 'toast'; - liveToast.classList.add(status); - - toastContent.textContent = content; - const toast = new bootstrap.Toast(liveToast); - toast.show(); - setTimeout(function() { - toast.hide(); - }, 8000); -} - export function makeRegister(check) { if (!check) return; From a6b7e3bd39ff4cf0b7109e11f8a9b8ebff588d1d Mon Sep 17 00:00:00 2001 From: Aktass Date: Mon, 15 Apr 2024 22:55:50 +0300 Subject: [PATCH 2/2] invite game overflow problem solved, tournaments link, chat invite fix, match history fix. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: temasictfic Co-authored-by: Enes Yağız --- indianpong/pong/consumer_chat.py | 2 +- indianpong/pong/consumer_pong.py | 2 +- indianpong/pong/game.py | 2 ++ indianpong/pong/rps.py | 2 ++ indianpong/pong/templates/room.html | 12 +++++-- indianpong/pong/views.py | 12 +++++-- indianpong/static/js/chat.js | 50 +++++++++++++++++++-------- indianpong/static/js/game/sockPong.js | 5 +++ 8 files changed, 66 insertions(+), 21 deletions(-) diff --git a/indianpong/pong/consumer_chat.py b/indianpong/pong/consumer_chat.py index c306f30..aeeb8aa 100644 --- a/indianpong/pong/consumer_chat.py +++ b/indianpong/pong/consumer_chat.py @@ -51,9 +51,9 @@ async def receive(self, text_data): # if accept it create game object and send link in form: /remote-game/invite/game_id to both # send message to room group that user accepted the game make it in client side accepted = data["accepted"] - group_name = f"{accepted}_{accepter}" accepted = await UserProfile.objects.aget(username=accepted) accepter = await UserProfile.objects.aget(username=self.user.username) + group_name = f"{accepted}-{accepter}" # create game object game = await Game.objects.acreate(group_name=group_name, player1=accepted, player2=accepter) await self.channel_layer.group_send( diff --git a/indianpong/pong/consumer_pong.py b/indianpong/pong/consumer_pong.py index fad57ec..3bc8ffd 100644 --- a/indianpong/pong/consumer_pong.py +++ b/indianpong/pong/consumer_pong.py @@ -428,7 +428,7 @@ async def chat_game(self, event): player1 = event['player1'] player2 = event['player2'] await self.send(text_data=json.dumps({ - 'type': 'tournament.match', + 'type': 'chat.game', 'game_id': game_id, 'player1': player1, 'player2': player2, diff --git a/indianpong/pong/game.py b/indianpong/pong/game.py index 9aefdd7..96ed0c0 100644 --- a/indianpong/pong/game.py +++ b/indianpong/pong/game.py @@ -195,6 +195,8 @@ def getScore(self, username): return self.player2.score def getDuration(self): + if self.start_time == 0: + return 0 if self.end_time == 0: self.end_time = time.time() return self.end_time - self.start_time diff --git a/indianpong/pong/rps.py b/indianpong/pong/rps.py index a1d9997..5cace21 100644 --- a/indianpong/pong/rps.py +++ b/indianpong/pong/rps.py @@ -107,6 +107,8 @@ def get_scores(self): return self.shaker1.score, self.shaker2.score def getDuration(self): + if self.start_time == 0: + return 0 if self.end_time == 0: self.end_time = time.time() return self.end_time - self.start_time diff --git a/indianpong/pong/templates/room.html b/indianpong/pong/templates/room.html index 03613c3..c6ab83d 100644 --- a/indianpong/pong/templates/room.html +++ b/indianpong/pong/templates/room.html @@ -108,7 +108,11 @@
- {{ message.content }} + {% if '/remote-game/tournament/' in message.content %} + Tournament Match + {% else %} + {{ message.content }} + {% endif %}
{{ message.get_short_date }}
@@ -121,7 +125,11 @@
- {{ message.content }} + {% if '/remote-game/tournament/' in message.content %} + Tournament Match + {% else %} + {{ message.content }} + {% endif %}
{{ message.get_short_date }}
diff --git a/indianpong/pong/views.py b/indianpong/pong/views.py index ddb6d38..b56d1d5 100644 --- a/indianpong/pong/views.py +++ b/indianpong/pong/views.py @@ -150,7 +150,7 @@ def auth_callback(request): data = { "grant_type": "authorization_code", "client_id": "u-s4t2ud-4b7a045a7cc7dd977eeafae807bd4947670f273cb30e1dd674f6bfa490ba6c45", # environ.get("FT_CLIENT_ID"), - "client_secret": "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", # environ.get("FT_CLIENT_SECRET"), + "client_secret": "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", # environ.get("FT_CLIENT_SECRET"), "code": code, "redirect_uri": f"{settings.BASE_URL}/auth_callback", } @@ -272,7 +272,9 @@ def profile_view(request, username): context = langs.get_langs(lang) game_records = Game.objects.filter( Q(player1=profile) | Q(player2=profile), - game_kind='pong' + game_kind='pong', + ).exclude( + game_duration=None ).order_by("-created_at") game_records_rps = Game.objects.filter( Q(player1=profile) | Q(player2=profile), @@ -855,11 +857,15 @@ def remote_game(request, game_type, game_id): if game_type == 'peer-to-peer' and game_id != 'new': raise Http404("Invalid game id for peer-to-peer. It should be 'new'.") - if game_type == 'tournament' or game_type == 'invite': + if game_type == 'tournament': game = get_object_or_404(Game, id=game_id) tournament = get_object_or_404(Tournament, id=game.tournament_id) if game.winner is not None: raise Http404("The game is already finished.") + elif game_type == 'invite': + game = get_object_or_404(Game, id=game_id) + if game.winner is not None: + raise Http404("The game is already finished.") lang = request.COOKIES.get('selectedLanguage', 'en') context = langs.get_langs(lang) diff --git a/indianpong/static/js/chat.js b/indianpong/static/js/chat.js index 1e043af..db7e30f 100644 --- a/indianpong/static/js/chat.js +++ b/indianpong/static/js/chat.js @@ -122,24 +122,34 @@ const langMessages = {
` return message - } +} - function messageOthers(data) { - var message = ` -
  • -
    -
    -
    -
    +function messageOthers(data) { + var message = ` +
  • +
    +
    +
    +

    ${data.message}

    -
    ${data.created_date}
    -
    +
    ${data.created_date}
    -
  • ` - return message +
    + ` + return message +} + +document.addEventListener('click', function(e) { + if (e.target.tagName === 'A' && e.target.hasAttribute('data-url')) { + var url = e.target.getAttribute('data-url'); + if (url.includes('/remote-game/tournament/')) { + e.preventDefault(); + swapApp(url); + } } +}); chatsocket.onmessage = function (e) { const cookie = document.cookie.split('; ').find(row => row.startsWith('selectedLanguage=')); @@ -249,11 +259,23 @@ const langMessages = { //console.log("invite button clicked"); chatsocket.send(JSON.stringify({ "action": "invite.game", - "inviter": user, - "invited": userNameOnChat, })) } + acceptButton.onclick = function (e) { + chatsocket.send(JSON.stringify({ + "action": "accept.game", + "accepted": userNameOnChat, + "accepter": user, + })) + } + + declineButton.onclick = function (e) { + chatsocket.send(JSON.stringify({ + "action": "decline.game", + })) + } + followButton.onclick = function (e) { const cookie = document.cookie.split('; ').find(row => row.startsWith('selectedLanguage=')); const lang = cookie ? cookie.split('=')[1] : 'en'; diff --git a/indianpong/static/js/game/sockPong.js b/indianpong/static/js/game/sockPong.js index b50c7de..6cabb10 100644 --- a/indianpong/static/js/game/sockPong.js +++ b/indianpong/static/js/game/sockPong.js @@ -323,6 +323,8 @@ matchsocket.onmessage = function (e) { break; case 'tournament.match': + checkbox.disabled = true; + leftArea.style.display = 'none'; player1.username = data.player1; player2.username = data.player2; my.game_id = data.game_id; @@ -346,9 +348,12 @@ matchsocket.onmessage = function (e) { break; case 'chat.game': + checkbox.disabled = true; + leftArea.style.display = 'none'; player1.username = data.player1; player2.username = data.player2; my.game_id = data.game_id; + my.opponent_username = data.player1 === my.username ? data.player2 : data.player1; if (lang === 'tr') showToast(`Chat maçı başladı! ${player1.username} vs ${player2.username}`, 'text-bg-success', 'bi bi-check-circle-fill'); else if (lang === 'hi')