mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2025-12-15 21:56:50 +01:00
Changed the player's pad movement behaviour
This commit is contained in:
parent
18c6580ae3
commit
067f24f5b8
@ -3,6 +3,7 @@
|
||||
import json
|
||||
import asyncio
|
||||
import random
|
||||
from .utils import endfortheouche
|
||||
|
||||
class Game:
|
||||
def __init__(self, game_id, player1, player2):
|
||||
@ -23,6 +24,10 @@ class Game:
|
||||
self.speed = 1
|
||||
self.game_loop_task = None
|
||||
self.ended = False
|
||||
self.p1_mov = 0
|
||||
self.p2_mov = 0
|
||||
self.bt1 = 0
|
||||
self.bt2 = 0
|
||||
|
||||
async def start_game(self):
|
||||
print(f"- Game #{self.game_id} STARTED")
|
||||
@ -32,6 +37,7 @@ class Game:
|
||||
while True:
|
||||
if self.botgame:
|
||||
await self.update_bot_position()
|
||||
await self.handle_pad_movement()
|
||||
self.update_game_state()
|
||||
await self.send_game_state()
|
||||
await asyncio.sleep(1/60) # Around 60 FPS
|
||||
@ -57,11 +63,13 @@ class Game:
|
||||
self.game_state['player1_position'] - 10 <= self.game_state['ball_position']['y'] <= self.game_state['player1_position'] + 90:
|
||||
if self.game_state['ball_velocity']['x'] < 0:
|
||||
self.game_state['ball_velocity']['x'] *= -1
|
||||
self.bt1 += 1
|
||||
self.update_ball_velocity()
|
||||
elif self.game_state['ball_position']['x'] >= 760 and \
|
||||
self.game_state['player2_position'] - 10 <= self.game_state['ball_position']['y'] <= self.game_state['player2_position'] + 90:
|
||||
if self.game_state['ball_velocity']['x'] > 0:
|
||||
self.game_state['ball_velocity']['x'] *= -1
|
||||
self.bt2 += 1
|
||||
self.update_ball_velocity()
|
||||
# Check for scoring
|
||||
if self.game_state['ball_position']['x'] <= 10:
|
||||
@ -107,14 +115,30 @@ class Game:
|
||||
return
|
||||
if player == self.player1:
|
||||
if key == 'arrowup':
|
||||
self.game_state['player1_position'] = max(self.game_state['player1_position'] - 25, 0)
|
||||
self.p1_mov = -1
|
||||
#self.game_state['player1_position'] = max(self.game_state['player1_position'] - 25, 0)
|
||||
elif key == 'arrowdown':
|
||||
self.game_state['player1_position'] = min(self.game_state['player1_position'] + 25, 300)
|
||||
self.p1_mov = 1
|
||||
#self.game_state['player1_position'] = min(self.game_state['player1_position'] + 25, 300)
|
||||
elif not self.botgame and player == self.player2:
|
||||
if key == 'arrowup':
|
||||
self.game_state['player2_position'] = max(self.game_state['player2_position'] - 25, 0)
|
||||
self.p2_mov = -1
|
||||
#self.game_state['player2_position'] = max(self.game_state['player2_position'] - 25, 0)
|
||||
elif key == 'arrowdown':
|
||||
self.game_state['player2_position'] = min(self.game_state['player2_position'] + 25, 300)
|
||||
self.p2_mov = 1
|
||||
#self.game_state['player2_position'] = min(self.game_state['player2_position'] + 25, 300)
|
||||
|
||||
async def handle_pad_movement(self):
|
||||
#print(f"P1 mov: {self.p1_mov}")
|
||||
#print(f"P2 mov: {self.p2_mov}")
|
||||
if self.p1_mov == -1:
|
||||
self.game_state['player1_position'] = max(self.game_state['player1_position'] - (5 * self.speed), 0)
|
||||
elif self.p1_mov == 1:
|
||||
self.game_state['player1_position'] = min(self.game_state['player1_position'] + (5 * self.speed), 300)
|
||||
if self.p2_mov == -1:
|
||||
self.game_state['player2_position'] = max(self.game_state['player2_position'] - (5 * self.speed), 0)
|
||||
elif self.p2_mov == 1:
|
||||
self.game_state['player2_position'] = min(self.game_state['player2_position'] + (5 * self.speed), 300)
|
||||
|
||||
async def end_game(self, disconnected_player=None):
|
||||
if not self.ended:
|
||||
@ -140,3 +164,22 @@ class Game:
|
||||
await self.player1.send(end_message)
|
||||
if not self.botgame:
|
||||
await self.player2.send(end_message)
|
||||
await endfortheouche(self.game_state['player1_name'], self.game_state['player2_name'],
|
||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
||||
self.bt1, self.bt2, 42, False, None)
|
||||
|
||||
### pour Theo ###
|
||||
# nickname player1
|
||||
# nickname player2
|
||||
# score p1
|
||||
# score p2
|
||||
# winner
|
||||
# ball touch p1
|
||||
# ball touch p2
|
||||
# match time
|
||||
# match type: 'quick match'
|
||||
|
||||
# match type: 'tournament'
|
||||
# -> tournament id
|
||||
|
||||
#endfortheouche(p1, p2, s_p1, s_p2, bt_p1, bt_p2, dur, is_tournoi, name_tournament)
|
||||
@ -1,4 +1,4 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-23 16:04
|
||||
# Generated by Django 5.0.7 on 2024-07-30 19:44
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
@ -17,6 +17,17 @@ class Migration(migrations.Migration):
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=100)),
|
||||
('total_match', models.PositiveSmallIntegerField(default=0)),
|
||||
('total_win', models.PositiveSmallIntegerField(default=0)),
|
||||
('p_win', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_adv_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('best_score', models.PositiveSmallIntegerField(default=0)),
|
||||
('m_nbr_ball_touch', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('total_duration', models.DurationField(blank=True, null=True)),
|
||||
('m_duration', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('num_participated_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
('num_won_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
|
||||
18
pong/game/migrations/0002_alter_match_duration.py
Normal file
18
pong/game/migrations/0002_alter_match_duration.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-31 13:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='duration',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
]
|
||||
@ -8,6 +8,17 @@ User.add_to_class('auth_token', models.CharField(max_length=100, null=True, blan
|
||||
|
||||
class Player(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
total_match = models.PositiveSmallIntegerField(default=0)
|
||||
total_win = models.PositiveSmallIntegerField(default=0)
|
||||
p_win = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
m_score_match = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
m_score_adv_match = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
best_score = models.PositiveSmallIntegerField(default=0)
|
||||
m_nbr_ball_touch = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
total_duration = models.DurationField(null=True, blank=True)
|
||||
m_duration = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
num_participated_tournaments = models.PositiveSmallIntegerField(default=0)
|
||||
num_won_tournaments = models.PositiveSmallIntegerField(default=0)
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
@ -29,7 +40,7 @@ class Match(models.Model):
|
||||
winner = models.ForeignKey('Player', related_name='won_matches',on_delete=models.CASCADE)
|
||||
nbr_ball_touch_p1 = models.PositiveIntegerField()
|
||||
nbr_ball_touch_p2 = models.PositiveIntegerField()
|
||||
duration = models.DurationField()
|
||||
duration = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||
date = models.DateField(auto_now_add=True)
|
||||
is_tournoi = models.BooleanField()
|
||||
tournoi = models.ForeignKey('Tournoi', related_name='matches', on_delete=models.SET_NULL, null=True)
|
||||
@ -44,7 +55,7 @@ class Match(models.Model):
|
||||
super().clean()
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
self.full_clean() # Appel de la méthode clean() avant d'enregistrer
|
||||
self.clean() # Appel de la méthode clean() avant d'enregistrer
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
|
||||
51
pong/game/templates/pong/match_list.html
Normal file
51
pong/game/templates/pong/match_list.html
Normal file
@ -0,0 +1,51 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Matches List</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Matches List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Player 1</th>
|
||||
<th>Player 2</th>
|
||||
<th>Score Player 1</th>
|
||||
<th>Score Player 2</th>
|
||||
<th>Winner</th>
|
||||
<th>Ball Touches Player 1</th>
|
||||
<th>Ball Touches Player 2</th>
|
||||
<th>Duration</th>
|
||||
<th>Date</th>
|
||||
<th>Is Tournament</th>
|
||||
<th>Tournament</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for match in matches %}
|
||||
<tr>
|
||||
<td>{{ match.id }}</td>
|
||||
<td>{{ match.player1.name }}</td>
|
||||
<td>{{ match.player2.name }}</td>
|
||||
<td>{{ match.score_player1 }}</td>
|
||||
<td>{{ match.score_player2 }}</td>
|
||||
<td>{{ match.winner.name }}</td>
|
||||
<td>{{ match.nbr_ball_touch_p1 }}</td>
|
||||
<td>{{ match.nbr_ball_touch_p2 }}</td>
|
||||
<td>{{ match.duration }}</td>
|
||||
<td>{{ match.date }}</td>
|
||||
<td>{{ match.is_tournoi }}</td>
|
||||
<td>{{ match.tournoi.name }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="12">No matches found.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
53
pong/game/templates/pong/player_list.html
Normal file
53
pong/game/templates/pong/player_list.html
Normal file
@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Players List</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Players List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>Total Matches</th>
|
||||
<th>Total Wins</th>
|
||||
<th>Win Percentage</th>
|
||||
<th>Average Match Score</th>
|
||||
<th>Average Opponent Score</th>
|
||||
<th>Best Score</th>
|
||||
<th>Average Ball Touches</th>
|
||||
<th>Total Duration</th>
|
||||
<th>Average Duration</th>
|
||||
<th>Participated Tournaments</th>
|
||||
<th>Won Tournaments</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for player in players %}
|
||||
<tr>
|
||||
<td>{{ player.id }}</td>
|
||||
<td>{{ player.name }}</td>
|
||||
<td>{{ player.total_match }}</td>
|
||||
<td>{{ player.total_win }}</td>
|
||||
<td>{{ player.p_win }}</td>
|
||||
<td>{{ player.m_score_match }}</td>
|
||||
<td>{{ player.m_score_adv_match }}</td>
|
||||
<td>{{ player.best_score }}</td>
|
||||
<td>{{ player.m_nbr_ball_touch }}</td>
|
||||
<td>{{ player.total_duration }}</td>
|
||||
<td>{{ player.m_duration }}</td>
|
||||
<td>{{ player.num_participated_tournaments }}</td>
|
||||
<td>{{ player.num_won_tournaments }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="13">No players found.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
37
pong/game/templates/pong/tournoi_list.html
Normal file
37
pong/game/templates/pong/tournoi_list.html
Normal file
@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Tournaments List</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Tournaments List</h1>
|
||||
<table border="1">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>Number of Players</th>
|
||||
<th>Date</th>
|
||||
<th>Winner</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for tournoi in tournois %}
|
||||
<tr>
|
||||
<td>{{ tournoi.id }}</td>
|
||||
<td>{{ tournoi.name }}</td>
|
||||
<td>{{ tournoi.nbr_player }}</td>
|
||||
<td>{{ tournoi.date }}</td>
|
||||
<td>{{ tournoi.winner.name }}</td>
|
||||
</tr>
|
||||
{% empty %}
|
||||
<tr>
|
||||
<td colspan="5">No tournaments found.</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@ -2,10 +2,14 @@
|
||||
|
||||
from django.urls import path
|
||||
from . import views
|
||||
from .views import player_list, tournoi_list, match_list
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.index, name='index'),
|
||||
path('check_user_exists/', views.check_user_exists, name='check_user_exists'),
|
||||
path('register_user/', views.register_user, name='register_user'),
|
||||
path('authenticate_user/', views.authenticate_user, name='authenticate_user'),
|
||||
path('players/', player_list, name='player_list'),
|
||||
path('matches/', match_list, name='match_list'),
|
||||
path('tournois/', tournoi_list, name='tournoi_list'),
|
||||
]
|
||||
|
||||
@ -1,33 +1,172 @@
|
||||
from myapp.models import Player, Tournoi, Match
|
||||
from .models import Player, Tournoi, Match
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.db.models import Max, Sum, F
|
||||
from datetime import timedelta
|
||||
from channels.db import database_sync_to_async
|
||||
|
||||
def create_player(name):
|
||||
player = Player(name=name)
|
||||
async def endfortheouche(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament):
|
||||
# Check if player p1 exists, if not create
|
||||
if not await database_sync_to_async(Player.objects.filter(name=p1).exists)():
|
||||
player_1 = await create_player(p1)
|
||||
else:
|
||||
player_1 = await database_sync_to_async(Player.objects.get)(name=p1)
|
||||
|
||||
# Check if player p2 exists, if not create
|
||||
if not await database_sync_to_async(Player.objects.filter(name=p2).exists)():
|
||||
player_2 = await create_player(p2)
|
||||
else:
|
||||
player_2 = await database_sync_to_async(Player.objects.get)(name=p2)
|
||||
|
||||
# create Match
|
||||
await create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
|
||||
|
||||
# Update data p1 et p2
|
||||
await uptdate_player_statistics(p1)
|
||||
await uptdate_player_statistics(p2)
|
||||
|
||||
@database_sync_to_async
|
||||
def create_player(
|
||||
name,
|
||||
total_match=0,
|
||||
total_win=0,
|
||||
p_win= None,
|
||||
m_score_match= None,
|
||||
m_score_adv_match= None,
|
||||
best_score=0,
|
||||
m_nbr_ball_touch= None,
|
||||
total_duration= None,
|
||||
m_duration= None,
|
||||
num_participated_tournaments=0,
|
||||
num_won_tournaments=0
|
||||
):
|
||||
if Player.objects.filter(name=name).exists():
|
||||
raise ValueError(f"A player with the name '{name}' already exists.")
|
||||
|
||||
player = Player(
|
||||
name=name,
|
||||
total_match = total_match,
|
||||
total_win = total_win,
|
||||
p_win = p_win,
|
||||
m_score_match = m_score_match,
|
||||
m_score_adv_match = m_score_adv_match,
|
||||
best_score = best_score,
|
||||
m_nbr_ball_touch = m_nbr_ball_touch,
|
||||
total_duration = total_duration,
|
||||
m_duration = m_duration,
|
||||
num_participated_tournaments = num_participated_tournaments,
|
||||
num_won_tournaments = num_won_tournaments
|
||||
)
|
||||
player.save()
|
||||
return player
|
||||
|
||||
def create_tournoi(name, nbr_player, date, winner=None):
|
||||
@database_sync_to_async
|
||||
def create_tournoi(name, nbr_player, date, winner):
|
||||
tournoi = Tournoi(name=name, nbr_player=nbr_player, date=date, winner=winner)
|
||||
tournoi.save()
|
||||
return tournoi
|
||||
|
||||
def create_match(player1, player2, score_player1=0, score_player2=0, winner=None, nbr_ball_touch_p1=0, nbr_ball_touch_p2=0, duration=None, is_tournoi=False, tournoi=None):
|
||||
@database_sync_to_async
|
||||
def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration, is_tournoi, tournoi):
|
||||
match = Match(
|
||||
player1=player1,
|
||||
player2=player2,
|
||||
score_player1=score_player1,
|
||||
score_player2=score_player2,
|
||||
winner=winner,
|
||||
nbr_ball_touch_p1=nbr_ball_touch_p1,
|
||||
nbr_ball_touch_p2=nbr_ball_touch_p2,
|
||||
duration=duration,
|
||||
is_tournoi=is_tournoi,
|
||||
tournoi=tournoi
|
||||
)
|
||||
|
||||
if score_player1 > score_player2:
|
||||
match.winner = match.player1
|
||||
elif score_player2 > score_player1:
|
||||
match.winner = match.player2
|
||||
else:
|
||||
match.winner = None
|
||||
|
||||
match.save()
|
||||
return match
|
||||
|
||||
def complete_match(match_id, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration):
|
||||
@database_sync_to_async
|
||||
def uptdate_player_statistics(player_name):
|
||||
player = get_object_or_404(Player, name=player_name)
|
||||
|
||||
# Filtrer les matchs où le joueur est joueur 1 ou joueur 2
|
||||
matches_as_player1 = Match.objects.filter(player1=player)
|
||||
matches_as_player2 = Match.objects.filter(player2=player)
|
||||
|
||||
# Calculer les statistiques
|
||||
total_match = matches_as_player1.count() + matches_as_player2.count()
|
||||
|
||||
if total_match == 0:
|
||||
# Eviter la division par zéro
|
||||
player.total_match = total_match
|
||||
player.total_win = 0
|
||||
player.p_win = 0
|
||||
player.m_score_match = 0
|
||||
player.m_score_adv_match = 0
|
||||
player.best_score = 0
|
||||
player.m_nbr_ball_touch = 0
|
||||
player.total_duration = 0
|
||||
player.m_duration = 0
|
||||
player.num_participated_tournaments = 0
|
||||
player.num_won_tournaments = 0
|
||||
player.save()
|
||||
return
|
||||
|
||||
won_matches = Match.objects.filter(winner=player)
|
||||
part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player1=player)
|
||||
part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player2=player)
|
||||
won_tourn = Tournoi.objects.filter(winner=player)
|
||||
|
||||
total_score = matches_as_player1.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
total_score += matches_as_player2.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
|
||||
total_score_adv = matches_as_player1.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
total_score_adv += matches_as_player2.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
|
||||
total_win = won_matches.count()
|
||||
p_win = (total_win / total_match) * 100
|
||||
|
||||
m_score_match = total_score / total_match
|
||||
m_score_adv_match = total_score_adv / total_match
|
||||
|
||||
nbr_ball_touch = matches_as_player1.aggregate(Sum('nbr_ball_touch_p1'))['nbr_ball_touch_p1__sum'] or 0
|
||||
nbr_ball_touch += matches_as_player2.aggregate(Sum('nbr_ball_touch_p2'))['nbr_ball_touch_p2__sum'] or 0
|
||||
m_nbr_ball_touch = nbr_ball_touch / total_match
|
||||
|
||||
total_duration = matches_as_player1.aggregate(Sum('duration'))['duration__sum']
|
||||
total_duration += matches_as_player2.aggregate(Sum('duration'))['duration__sum']
|
||||
m_duration = total_duration / total_match
|
||||
|
||||
""" total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
total_win_tourn = won_tourn.count()
|
||||
p_win_tourn = (total_win_tourn / total_tourn_p) * 100 if total_tourn_p else 0
|
||||
"""
|
||||
best_score_as_player1 = matches_as_player1.aggregate(Max('score_player1'))['score_player1__max'] or 0
|
||||
best_score_as_player2 = matches_as_player2.aggregate(Max('score_player2'))['score_player2__max'] or 0
|
||||
best_score = max(best_score_as_player1, best_score_as_player2)
|
||||
|
||||
# Mettre à jour les champs du joueur
|
||||
player.total_match = total_match
|
||||
player.total_win = total_win
|
||||
player.p_win = p_win
|
||||
player.m_score_match = m_score_match
|
||||
player.m_score_adv_match = m_score_adv_match
|
||||
player.best_score = best_score
|
||||
player.m_nbr_ball_touch = m_nbr_ball_touch
|
||||
player.total_duration = total_duration
|
||||
player.m_duration = m_duration
|
||||
""" player.num_participated_tournaments = total_tourn_p
|
||||
player.num_won_tournaments = total_win_tourn """
|
||||
|
||||
player.save()
|
||||
|
||||
|
||||
""" def complete_match(match_id, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration):
|
||||
try:
|
||||
match = Match.objects.get(id=match_id)
|
||||
except Match.DoesNotExist:
|
||||
@ -47,9 +186,9 @@ def complete_match(match_id, score_player1, score_player2, nbr_ball_touch_p1, nb
|
||||
match.winner = None
|
||||
|
||||
match.save()
|
||||
return match
|
||||
return match """
|
||||
|
||||
def complete_tournoi(tournoi_id, player):
|
||||
""" def complete_tournoi(tournoi_id, player):
|
||||
try:
|
||||
tournoi = Tournoi.objects.get(id = tournoi_id)
|
||||
except Tournoi.DoesNotExist:
|
||||
@ -57,50 +196,7 @@ def complete_tournoi(tournoi_id, player):
|
||||
|
||||
tournoi.winner = player
|
||||
tournoi.save()
|
||||
return tournoi
|
||||
|
||||
def player_statistics(request, player_name):
|
||||
player = get_object_or_404(Player, nam = player_name)
|
||||
|
||||
#filtre on tab
|
||||
matches_as_player1 = Match.objects.filter(player1=player)
|
||||
matches_as_player2 = Match.objects.filter(player2=player)
|
||||
won_matches = Match.objects.filter(winner=player)
|
||||
part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player1=player)
|
||||
part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player2=player)
|
||||
won_tourn = Tournoi.objects.filter(winner=player)
|
||||
|
||||
# calulate stat
|
||||
total_match = match_as_player1.count() + match_as_player2.count()
|
||||
total_score = sum([match.score_player1 for match in matches_as_player1 ]) + sum([match.score_player2 for match in matches_as_player2])
|
||||
total_score_adv = sum([match.score_player2 for match in matches_as_player1 ]) + sum([match.score_player1 for match in matches_as_player2])
|
||||
total_win = won_matches.count()
|
||||
p_win = (total_win / total_match) * 100
|
||||
m_score_match = total_score / total_match
|
||||
m_score_adv_match = total_score_adv / total_match
|
||||
nbr_ball_touch = sum([match.nbr_ball_touch_p1 for match in matches_as_player1]) + sum([match.nbr_ball_touch_p2 for match in matches_as_player2])
|
||||
m_nbr_ball_touch = nbr_ball_touch / total_match
|
||||
total_duration = sum([match.duration for match in matches_as_player1]) + sum(match.duration for match in matches_as_player2)
|
||||
m_duration = total_duration / total_match
|
||||
total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
total_win_tourn = won_tourn.count()
|
||||
p_win_tourn = (total_win_tourn / total_tourn_p) * 100
|
||||
|
||||
best_score_as_player1 = matches_as_player1.aggregate(Max('score_player1'))['score_player1__max']
|
||||
best_score_as_player2 = matches_as_player2.aggregate(Max('score_player2'))['score_player2__max']
|
||||
best_score = max(best_score_as_player1, best_score_as_player2)
|
||||
|
||||
data = {
|
||||
'player_name': player.name,
|
||||
'number of match played' : total_match
|
||||
'number of win (matches)' : total_win
|
||||
'pourcentage of victory' : p_win
|
||||
'num_participated_tournaments': num_participated_tournaments,
|
||||
'num_won_tournaments': num_won_tournaments
|
||||
}
|
||||
|
||||
return data
|
||||
return tournoi """
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -5,6 +5,9 @@ from django.shortcuts import render
|
||||
def index(request):
|
||||
return render(request, 'index.html')
|
||||
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from .models import Player, Tournoi, Match
|
||||
from .utils import create_player, create_tournoi, create_match
|
||||
from django.http import JsonResponse
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth import authenticate
|
||||
@ -62,3 +65,138 @@ def get_or_create_token(user):
|
||||
user.save()
|
||||
break
|
||||
return user.auth_token
|
||||
|
||||
|
||||
####################### THEOUCHE PART ############################
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
def create_player_view(request):
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
name = data.get('name')
|
||||
|
||||
# Vérifier que le nom est présent
|
||||
if not name:
|
||||
return JsonResponse({'error': 'Name is required'}, status=400)
|
||||
|
||||
# Appeler la fonction create_player et traiter les exceptions
|
||||
player = create_player(
|
||||
name=name,
|
||||
total_match=data.get('total_match', 0),
|
||||
total_win=data.get('total_win', 0),
|
||||
p_win=data.get('p_win'),
|
||||
m_score_match=data.get('m_score_match'),
|
||||
m_score_adv_match=data.get('m_score_adv_match'),
|
||||
best_score=data.get('best_score', 0),
|
||||
m_nbr_ball_touch=data.get('m_nbr_ball_touch'),
|
||||
total_duration=data.get('total_duration'),
|
||||
m_duration=data.get('m_duration'),
|
||||
num_participated_tournaments=data.get('num_participated_tournaments', 0),
|
||||
num_won_tournaments=data.get('num_won_tournaments', 0)
|
||||
)
|
||||
return JsonResponse({'id': player.id, 'name': player.name})
|
||||
|
||||
except ValueError as e:
|
||||
# Erreur spécifique à la validation
|
||||
return JsonResponse({'error': str(e)}, status=400)
|
||||
except json.JSONDecodeError:
|
||||
# Erreur de décodage JSON
|
||||
return JsonResponse({'error': 'Invalid JSON format'}, status=400)
|
||||
except Exception as e:
|
||||
# Erreur générale
|
||||
return JsonResponse({'error': 'An unexpected error occurred', 'details': str(e)}, status=500)
|
||||
|
||||
# Méthode HTTP non supportée
|
||||
return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
|
||||
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
def create_tournoi_view(request):
|
||||
if request.method == 'POST':
|
||||
data = json.loads(request.body)
|
||||
name = data.get('name')
|
||||
nbr_player = data.get('nbr_player')
|
||||
date = data.get('date')
|
||||
winner_id = data.get('winner_id')
|
||||
if not (name and nbr_player and date):
|
||||
return JsonResponse({'error': 'Name, number of players, and date are required'}, status=400)
|
||||
|
||||
winner = None
|
||||
if winner_id:
|
||||
try:
|
||||
winner = Player.objects.get(id=winner_id)
|
||||
except Player.DoesNotExist:
|
||||
return JsonResponse({'error': 'Winner not found'}, status=404)
|
||||
|
||||
tournoi = create_tournoi(name, nbr_player, date, winner)
|
||||
return JsonResponse({
|
||||
'id': tournoi.id,
|
||||
'name': tournoi.name,
|
||||
'nbr_player': tournoi.nbr_player,
|
||||
'date': tournoi.date.isoformat(),
|
||||
'winner': winner.id if winner else None
|
||||
})
|
||||
return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
|
||||
|
||||
@csrf_exempt
|
||||
def create_match_view(request):
|
||||
if request.method == 'POST':
|
||||
data = json.loads(request.body)
|
||||
player1_id = data.get('player1_id')
|
||||
player2_id = data.get('player2_id')
|
||||
score_player1 = data.get('score_player1', 0)
|
||||
score_player2 = data.get('score_player2', 0)
|
||||
nbr_ball_touch_p1 = data.get('nbr_ball_touch_p1', 0)
|
||||
nbr_ball_touch_p2 = data.get('nbr_ball_touch_p2', 0)
|
||||
duration = data.get('duration')
|
||||
is_tournoi = data.get('is_tournoi', False)
|
||||
tournoi_id = data.get('tournoi_id')
|
||||
|
||||
if not (player1_id and player2_id and duration):
|
||||
return JsonResponse({'error': 'Player IDs and duration are required'}, status=400)
|
||||
|
||||
try:
|
||||
player1 = Player.objects.get(id=player1_id)
|
||||
player2 = Player.objects.get(id=player2_id)
|
||||
except Player.DoesNotExist:
|
||||
return JsonResponse({'error': 'One or both players not found'}, status=404)
|
||||
|
||||
tournoi = None
|
||||
if tournoi_id:
|
||||
try:
|
||||
tournoi = Tournoi.objects.get(id=tournoi_id)
|
||||
except Tournoi.DoesNotExist:
|
||||
return JsonResponse({'error': 'Tournoi not found'}, status=404)
|
||||
|
||||
match = create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration, is_tournoi, tournoi)
|
||||
return JsonResponse({
|
||||
'id': match.id,
|
||||
'player1': match.player1.id,
|
||||
'player2': match.player2.id,
|
||||
'score_player1': match.score_player1,
|
||||
'score_player2': match.score_player2,
|
||||
'nbr_ball_touch_p1': match.nbr_ball_touch_p1,
|
||||
'nbr_ball_touch_p2': match.nbr_ball_touch_p2,
|
||||
'duration': str(match.duration),
|
||||
'is_tournoi': match.is_tournoi,
|
||||
'tournoi': match.tournoi.id if match.tournoi else None
|
||||
})
|
||||
return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
|
||||
|
||||
|
||||
def player_list(request):
|
||||
players = Player.objects.all()
|
||||
return render(request, 'pong/player_list.html', {'players': players})
|
||||
|
||||
def match_list(request):
|
||||
matches = Match.objects.select_related('player1', 'player2', 'winner', 'tournoi').all()
|
||||
return render(request, 'pong/match_list.html', {'matches': matches})
|
||||
|
||||
def tournoi_list(request):
|
||||
tournois = Tournoi.objects.select_related('winner').all()
|
||||
return render(request, 'pong/tournoi_list.html', {'tournois': tournois})
|
||||
|
||||
####################### THEOUCHE PART ############################
|
||||
@ -70,7 +70,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
async function checkUserExists(username) {
|
||||
const response = await fetch('/api/check_user_exists/', {
|
||||
const response = await fetch('/check_user_exists/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
@ -105,7 +105,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
async function registerUser(username, password) {
|
||||
const response = await fetch('/api/register_user/', {
|
||||
const response = await fetch('/register_user/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
@ -137,7 +137,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
async function authenticateUser(username, password) {
|
||||
const response = await fetch('/api/authenticate_user/', {
|
||||
const response = await fetch('/authenticate_user/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
|
||||
@ -8,7 +8,7 @@ from django.conf.urls.static import static
|
||||
urlpatterns = [
|
||||
# Disable the admin page
|
||||
# path('admin/', admin.site.urls),
|
||||
path('api/', include('pong.game.urls')),
|
||||
# path('api/', include('pong.game.urls')),
|
||||
path('', include('pong.game.urls')),
|
||||
]
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user