Skip to content

Commit

Permalink
Code: the game is being created and updated from the app itself. Miss…
Browse files Browse the repository at this point in the history
…ing merge to update the game statistics.
  • Loading branch information
Nuno-Jesus committed Oct 1, 2024
1 parent be4c2eb commit e8f3589
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 43 deletions.
3 changes: 2 additions & 1 deletion backend/pong/templates/pages/gamelocal.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
<div id="camera"></div>
</div>

<script id="game-engine" type="module" game-type="local" src="{% static 'js/game/main.js' %}" ></script>
<script id="game-engine" type="module" src="{% static 'js/game/main.js' %}"
data-user-id="{{ user.id }}" game-type="Local"></script>
{% endblock %}
1 change: 1 addition & 0 deletions backend/pong/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@

#! Debug
path('tournaments', views.tournament_list, name='tournament-list'),
path('debug/games/<int:game_id>', views.get_game, name='debug-get-game'),

]

Expand Down
30 changes: 23 additions & 7 deletions backend/pong/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 ---------------------------------------

Expand Down
6 changes: 0 additions & 6 deletions backend/static/js/game/Ball.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
47 changes: 32 additions & 15 deletions backend/static/js/game/GameController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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() {
Expand All @@ -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);
Expand Down
42 changes: 28 additions & 14 deletions backend/static/js/game/GameStats.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
/* ::: :::::::: */
/* GameStats.js :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ncarvalh <ncarvalh@student.42.fr> +#+ +:+ +#+ */
/* By: crypted <crypted@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* 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 */
/* */
/* ************************************************************************** */

Expand All @@ -20,36 +20,39 @@ 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) {
const goal = {
'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);
console.log(goal);

if (this.gameHasEnded()){
this.calculateSmallStats();
this.calculateAdvancedStats();
this.sendGameResults();
}
}
Expand Down Expand Up @@ -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,
Expand All @@ -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() {
Expand Down

0 comments on commit e8f3589

Please sign in to comment.