diff --git a/backend/pong/templates/pages/gamelocal.html b/backend/pong/templates/pages/gamelocal.html index 7d8ab4a..be85113 100644 --- a/backend/pong/templates/pages/gamelocal.html +++ b/backend/pong/templates/pages/gamelocal.html @@ -21,5 +21,6 @@
- + {% endblock %} \ No newline at end of file diff --git a/backend/pong/urls.py b/backend/pong/urls.py index 1062c83..099aec1 100644 --- a/backend/pong/urls.py +++ b/backend/pong/urls.py @@ -101,6 +101,7 @@ #! Debug path('tournaments', views.tournament_list, name='tournament-list'), + path('debug/games/', views.get_game, name='debug-get-game'), ] diff --git a/backend/pong/views.py b/backend/pong/views.py index 8c82698..48e1002 100644 --- a/backend/pong/views.py +++ b/backend/pong/views.py @@ -75,7 +75,7 @@ def profile(request, id): user = get_object_or_404(Users, id=id) games = Games.objects.filter(Q(Q(user1_id=user_profile.id) | Q(user2_id=user_profile.id)) - ).exclude(type="Tournament").order_by('-created_at') + ).exclude(type="Tournament").order_by('-created_at') tournament_response = tournament_list_user(request, user_profile.id) user_tournaments = json.loads(tournament_response.content) stats_response = user_stats(request, user_profile.id) @@ -529,23 +529,39 @@ def game_update(request, game_id): game.nb_goals_user2 = data['nb_goals_user2'] player1 = Users.objects.get(pk=game.user1_id.id) - player2 = Users.objects.get(pk=game.user2_id.id) + player1.status = "Online" + player1.save() + player2 = None + if game.type != "Local": + player2 = Users.objects.get(pk=game.user2_id.id) + player2.status = "Online" + player2.save() if data['nb_goals_user1'] > data['nb_goals_user2']: game.winner_id = player1 - else: + elif data['nb_goals_user1'] > data['nb_goals_user2'] and game.type != "Local": game.winner_id = player2 game.save() - player1.status = "Online" - player1.save() - player2.status = "Online" - player2.save() + gameStats = GamesStats.objects.create() + data = GamesSerializer(game).data return JsonResponse(data, status=200) +@csrf_exempt +def get_game(request, game_id): + if request.method !='GET': + return JsonResponse({'message': 'Method not allowed'}, status=405) + if request.method == 'GET': + try: + game = Games.objects.get(id=game_id) + serializer = GamesSerializer(game) + return JsonResponse({'message': 'Game Info', 'data': serializer.data}, status=200) + except Games.DoesNotExist: + return JsonResponse({'message': 'Game not found.'}, status=404) + #! --------------------------------------- Tournaments --------------------------------------- diff --git a/backend/static/js/game/Ball.js b/backend/static/js/game/Ball.js index 1b9d9d6..a4f35bd 100644 --- a/backend/static/js/game/Ball.js +++ b/backend/static/js/game/Ball.js @@ -39,15 +39,9 @@ export class Ball extends THREE.Object3D { const { rightBoundary, leftBoundary } = arena; if (this.position.x - this.radius <= leftBoundary.position.x) - { - this.reset(); return player; - } else if (this.position.x + this.radius >= rightBoundary.position.x) - { - this.reset(); return enemy; - } return null; } diff --git a/backend/static/js/game/GameController.js b/backend/static/js/game/GameController.js index 59a6b4a..6eb4058 100644 --- a/backend/static/js/game/GameController.js +++ b/backend/static/js/game/GameController.js @@ -11,7 +11,6 @@ export class GameController extends THREE.Group { super(); this.gameType = gameType; - this.gameId = 0; this.keybinds = null; this.arena = null; this.ball = null; @@ -23,30 +22,46 @@ export class GameController extends THREE.Group { this.build(); } - init() { - this.keybinds = { - 'w': false, 's': false, - 'ArrowUp': false, 'ArrowDown': false - }; + async init() { this.arena = new Arena({}); this.ball = new Ball({}); - this.player = new Player(1, 'Nuno', [-25, 0, 0], {'up': 'w', 'down': 's'}); - if (this.gameType == "local") + this.player = new LocalPlayer(1, 'Nuno', [-25, 0, 0], {'up': 'w', 'down': 's'}); + if (this.gameType == "Local") this.enemy = new LocalPlayer(2, 'Andreia', [25, 0, 0], {'up': 'ArrowUp', 'down': 'ArrowDown'}); - // else if (this.gameType == "remote") - // this.enemy = new RemotePlayer(2, 'Andreia', [25, 0, 0], {'up': 'ArrowUp', 'down': 'ArrowDown'}); - // else - // this.enemy = new AIPlayer(2, 'Andreia', [25, 0, 0], {'up': 'ArrowUp', 'down': 'ArrowDown'}); this.stats = new GameStats(this.player, this.enemy); + this.keybinds = { + 'w': false, 's': false, + 'ArrowUp': false, 'ArrowDown': false + }; document.addEventListener('keydown', (event) => { - if (event.key in this.keybinds) + if (event.key in this.keybinds) this.keybinds[event.key] = true; }); document.addEventListener('keyup', (event) => { - if (event.key in this.keybinds) + if (event.key in this.keybinds) this.keybinds[event.key] = false; }); + + const formData = { + "user1_id": document.getElementById('game-engine').getAttribute('data-user-id'), + "user2_id": null, + "type": document.getElementById('game-engine').getAttribute('game-type') + } + + const response = await fetch(`/games/create`, { + method: 'POST', + body: JSON.stringify(formData), + headers: { + 'Content-Type': 'application/json', + } + }); + + const data = await response.json(); + console.log(data); + this.stats.gameId = data.id; + console.log(this.stats.gameId); + } build() { @@ -63,8 +78,10 @@ export class GameController extends THREE.Group { return ; const scorer = this.ball.move(this); - if (scorer != null) + if (scorer != null) { this.stats.registerGoal(scorer, this.ball); + this.ball.reset(); + } if (this.stats.winner != null) { this.remove(this.ball); diff --git a/backend/static/js/game/GameStats.js b/backend/static/js/game/GameStats.js index 97d2f01..10c5c98 100644 --- a/backend/static/js/game/GameStats.js +++ b/backend/static/js/game/GameStats.js @@ -3,10 +3,10 @@ /* ::: :::::::: */ /* GameStats.js :+: :+: :+: */ /* +:+ +:+ +:+ */ -/* By: ncarvalh +#+ +:+ +#+ */ +/* By: crypted +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/09/30 18:34:16 by ncarvalh #+# #+# */ -/* Updated: 2024/09/30 19:01:48 by ncarvalh ### ########.fr */ +/* Updated: 2024/10/01 21:41:00 by crypted ### ########.fr */ /* */ /* ************************************************************************** */ @@ -20,21 +20,23 @@ export class GameStats { this.goals = []; this.loser = null; this.winner = null; + this.gameId = 0; this.gameStats = {}; this.scoredFirst = null; - this.start = null; + this.startTime = null; this.init(); } init() { - this.start = new Date().getTime(); + this.startTime = new Date().getTime(); this.score[this.player.username] = 0; this.score[this.enemy.username] = 0; - this.goals = TEST_GOALS; - this.calculateSmallStats(); - this.calculateAdvancedStats(); - this.sendGameResults(); + //! Testing + // this.goals = TEST_GOALS; + // this.calculateSmallStats(); + // this.calculateAdvancedStats(); + // this.sendGameResults(); } registerGoal(scorer, ball) { @@ -42,7 +44,7 @@ export class GameStats { 'timestamp': new Date().toISOString(), 'user': scorer.id, 'rally_length': ball.rally, - 'ball_speed': ball.speed, + 'ball_speed': Math.abs(ball.speed.x), }; this.score[scorer.username] += 1; this.goals.push(goal); @@ -50,6 +52,7 @@ export class GameStats { if (this.gameHasEnded()){ this.calculateSmallStats(); + this.calculateAdvancedStats(); this.sendGameResults(); } } @@ -113,13 +116,13 @@ export class GameStats { this.gameStats["most_consecutive_goals"] = Math.max(stats[p1].maxConsecutive, stats[p2].maxConsecutive); this.gameStats["mcg_user"] = stats[p1].maxConsecutive > stats[p2].maxConsecutive ? p1 : p2; this.gameStats["biggest_lead"] = Math.max(stats[p1].maxLead, stats[p2].maxLead); - this.gameStats["bl_user"] = stats[p1].maxLead > stats[p2].maxLead ? p1 : p2; + this.gameStats["bg_user"] = stats[p1].maxLead > stats[p2].maxLead ? p1 : p2; } - sendGameResults() { + async sendGameResults() { const now = new Date().getTime(); - const data = { - "duration": Math.round((now - this.start) / 1000), + const formData = { + "duration": Math.round((now - this.startTime) / 1000), "nb_goals_user1": this.score[this.player.username], "nb_goals_user2": this.score[this.enemy.username], "game_stats": this.gameStats, @@ -131,10 +134,21 @@ export class GameStats { }, "goals": this.goals }; - console.log(data); + console.log(formData); this.winner = this.score[this.player.username] == MAX_GOALS ? this.player : this.enemy; this.loser = this.winner == this.player ? this.enemy : this.player; + + const response = await fetch(`/games/update/${this.gameId}`, { + method: 'POST', + body: JSON.stringify(formData), + headers: { + 'Content-Type': 'application/json', + } + }); + + const responseData = await response.json(); + console.log(responseData); } gameHasEnded() {