mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2025-12-16 14:07:49 +01:00
Player register ok
This commit is contained in:
parent
ea24accbc4
commit
e8f46e211c
4
makefile
4
makefile
@ -9,7 +9,7 @@ ELK_COMPOSE=docker compose -f $(ELK_COMPOSE_FILE) -p $(ELK_PROJECT_NAME)
|
|||||||
|
|
||||||
CONTAINER=$(c)
|
CONTAINER=$(c)
|
||||||
|
|
||||||
up:
|
up: down
|
||||||
$(COMPOSE) build
|
$(COMPOSE) build
|
||||||
$(COMPOSE) up -d $(CONTAINER) || true
|
$(COMPOSE) up -d $(CONTAINER) || true
|
||||||
|
|
||||||
@ -22,6 +22,8 @@ down:
|
|||||||
destroy:
|
destroy:
|
||||||
$(COMPOSE) down -v --rmi all
|
$(COMPOSE) down -v --rmi all
|
||||||
|
|
||||||
|
re : down destroy up
|
||||||
|
|
||||||
# Manage ELK stack
|
# Manage ELK stack
|
||||||
|
|
||||||
elk-up:
|
elk-up:
|
||||||
|
|||||||
@ -4,10 +4,13 @@ import json
|
|||||||
import asyncio
|
import asyncio
|
||||||
import random
|
import random
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from .utils import handle_game_data, getlen
|
from .utils import handle_game_data, getlen, create_player, create_match
|
||||||
from asgiref.sync import sync_to_async
|
from asgiref.sync import sync_to_async
|
||||||
from .models import Tournoi
|
from .models import Tournoi
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
executor = ThreadPoolExecutor(max_workers=5)
|
||||||
|
lock = asyncio.Lock()
|
||||||
class Game:
|
class Game:
|
||||||
# Global variable to handle the using of the database
|
# Global variable to handle the using of the database
|
||||||
USING_DB = False
|
USING_DB = False
|
||||||
@ -58,6 +61,7 @@ class Game:
|
|||||||
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']}) --- ({self})")
|
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']}) --- ({self})")
|
||||||
self.game_loop_task = asyncio.create_task(self.game_loop())
|
self.game_loop_task = asyncio.create_task(self.game_loop())
|
||||||
print(f" Begin MATCH at: {self.start_time}")
|
print(f" Begin MATCH at: {self.start_time}")
|
||||||
|
await sync_to_async(create_player)(self.game_state['player1_name'], self.game_state['player2_name'])
|
||||||
|
|
||||||
async def game_loop(self):
|
async def game_loop(self):
|
||||||
print(" In the game loop..")
|
print(" In the game loop..")
|
||||||
@ -250,52 +254,22 @@ class Game:
|
|||||||
if not self.localgame:
|
if not self.localgame:
|
||||||
await self.player2.send(end_message)
|
await self.player2.send(end_message)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
attempt = 0
|
|
||||||
max_attempts = 10 # Limite le nombre de tentatives
|
|
||||||
success = False
|
|
||||||
|
|
||||||
print(f"Try to save game #{self.game_id} ({self})")
|
print(f"Try to save game #{self.game_id} ({self})")
|
||||||
#while attempt < max_attempts and not success:
|
|
||||||
try:
|
|
||||||
if hasattr(self, 'tournament'):
|
|
||||||
print(f"*** Game #{self.game_id} from tournament: {self.tournament.tournoi_reg.name} ENDED ***")
|
|
||||||
|
|
||||||
# Essaye d'appeler handle_game_data
|
|
||||||
result = await sync_to_async(handle_game_data)(
|
|
||||||
self.game_state['player1_name'], self.game_state['player2_name'],
|
|
||||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
|
||||||
self.bt1, self.bt2, duration, True, self.tournament.tournoi_reg
|
|
||||||
)
|
|
||||||
|
|
||||||
# Vérification explicite de la réussite
|
|
||||||
if result is not None: # Si handle_game_data peut retourner un résultat indicatif
|
|
||||||
success = True
|
|
||||||
print(f"*** Game #{self.game_id} from tournament: {self.tournament.tournoi_reg.name} is REGISTERED ***")
|
|
||||||
else:
|
|
||||||
raise ValueError("handle_game_data returned an unexpected result")
|
|
||||||
|
|
||||||
else:
|
avd, d = (True, self.tournament.tournoi_reg) if hasattr(self, 'tournament') else (False, None)
|
||||||
print(f"*** Game #{self.game_id} simple game ENDED ***")
|
|
||||||
result = await sync_to_async(handle_game_data)(
|
|
||||||
self.game_state['player1_name'], self.game_state['player2_name'],
|
|
||||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
|
||||||
self.bt1, self.bt2, duration, False, None
|
|
||||||
)
|
|
||||||
print("result done !!!")
|
|
||||||
|
|
||||||
if result is not None:
|
|
||||||
success = True
|
# Essaye d'appeler handle_game_data
|
||||||
print(f"Non-tournament game {self.game_id} data registered")
|
print("TRY CREATE MATCH")
|
||||||
else:
|
|
||||||
raise ValueError("handle_game_data returned an unexpected result")
|
|
||||||
|
|
||||||
except Exception as e:
|
await sync_to_async(create_match)(
|
||||||
attempt += 1
|
self.game_state['player1_name'], self.game_state['player2_name'],
|
||||||
print(f"Attempt {attempt}: Failed to register game data - {e}")
|
self.game_state['player1_score'], self.game_state['player2_score'],
|
||||||
await asyncio.sleep(1) # Délai avant de réessayer
|
self.bt1, self.bt2, duration, avd, d
|
||||||
|
)
|
||||||
|
|
||||||
if attempt >= max_attempts:
|
print("MATCH OK")
|
||||||
print("Max attempts reached. Could not register game data.")
|
|
||||||
#break
|
|
||||||
@ -0,0 +1,28 @@
|
|||||||
|
# Generated by Django 5.1.1 on 2024-09-14 09:10
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('game', '0001_initial'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='match',
|
||||||
|
name='player1',
|
||||||
|
field=models.CharField(max_length=100),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='match',
|
||||||
|
name='player2',
|
||||||
|
field=models.CharField(max_length=100),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='match',
|
||||||
|
name='winner',
|
||||||
|
field=models.CharField(max_length=100),
|
||||||
|
),
|
||||||
|
]
|
||||||
@ -26,11 +26,11 @@ class Tournoi(models.Model):
|
|||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
class Match(models.Model):
|
class Match(models.Model):
|
||||||
player1 = models.ForeignKey('Player', related_name='match_as_player1', on_delete=models.CASCADE)
|
player1 = models.CharField(max_length=100)
|
||||||
player2 = models.ForeignKey('Player', related_name='match_as_player2', on_delete=models.CASCADE)
|
player2 = models.CharField(max_length=100)
|
||||||
score_player1 = models.PositiveSmallIntegerField()
|
score_player1 = models.PositiveSmallIntegerField()
|
||||||
score_player2 = models.PositiveSmallIntegerField()
|
score_player2 = models.PositiveSmallIntegerField()
|
||||||
winner = models.ForeignKey('Player', related_name='won_matches',on_delete=models.CASCADE, null=True)
|
winner = models.CharField(max_length=100)
|
||||||
nbr_ball_touch_p1 = models.PositiveIntegerField()
|
nbr_ball_touch_p1 = models.PositiveIntegerField()
|
||||||
nbr_ball_touch_p2 = models.PositiveIntegerField()
|
nbr_ball_touch_p2 = models.PositiveIntegerField()
|
||||||
duration = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
duration = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
|
||||||
|
|||||||
@ -110,8 +110,7 @@ class TournamentMatchMaker:
|
|||||||
await asyncio.sleep(1) # Wait for 1 second before checking again
|
await asyncio.sleep(1) # Wait for 1 second before checking again
|
||||||
# Get winners for the next round
|
# Get winners for the next round
|
||||||
players = self.get_round_winners()
|
players = self.get_round_winners()
|
||||||
print(f"Round {self.current_round} finished. {len(players)} players advancing.")
|
print(f"Round {self.current_round} finished. {len(players)} players advancing.")
|
||||||
await asyncio.sleep(10)
|
|
||||||
# Tournament has ended
|
# Tournament has ended
|
||||||
await self.update_brackets()
|
await self.update_brackets()
|
||||||
await self.end_tournament(players[0] if players else None)
|
await self.end_tournament(players[0] if players else None)
|
||||||
|
|||||||
@ -2,53 +2,71 @@ from .models import Player, Tournoi, Match
|
|||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
from django.db.models import Max, Sum, F
|
from django.db.models import Max, Sum, F
|
||||||
from datetime import timedelta
|
|
||||||
from channels.db import database_sync_to_async
|
|
||||||
from asgiref.sync import sync_to_async
|
from asgiref.sync import sync_to_async
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
players_name_list = []
|
||||||
|
|
||||||
def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament):
|
def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament):
|
||||||
try:
|
try:
|
||||||
print("Here !!!!!!!!")
|
print("Here !!!!!!!!")
|
||||||
player_1 = get_or_create_player(p1)
|
#get_or_create_player(p1, p2)
|
||||||
print("FIRST PLAYER REGISTERD")
|
#print("FIRST PLAYER REGISTERD")
|
||||||
player_2 = get_or_create_player(p2)
|
#await sync_to_async(get_or_create_player)(p2)
|
||||||
print("SECOND PLAYER REGISTERD")
|
#print("SECOND PLAYER REGISTERD")
|
||||||
|
|
||||||
|
|
||||||
if (not player_1 or not player_2) :
|
|
||||||
print("AIIEJJDFKJBDBKJJKB PROBLEME ORIOL ")
|
|
||||||
print("CHAKU & THEOUCHE are the BEST")
|
print("CHAKU & THEOUCHE are the BEST")
|
||||||
create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
|
create_match(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
|
||||||
print("and ADRIANO is the PEST")
|
print("and ADRIANO is the PEST")
|
||||||
|
|
||||||
update_player_statistics(p1)
|
#update_player_statistics(p1)
|
||||||
print("END UPDATE FISRT PLAYER")
|
print("END UPDATE FISRT PLAYER")
|
||||||
update_player_statistics(p2)
|
#update_player_statistics(p2)
|
||||||
print("END UPDATE SECOND PLAYER")
|
print("END UPDATE SECOND PLAYER")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error in endfortheouche: {e}")
|
print(f"Error in endfortheouche: {e}")
|
||||||
|
|
||||||
|
|
||||||
def get_or_create_player(name):
|
def create_player(name_p1, name_p2):
|
||||||
print("Get or create player")
|
print("Get or create player")
|
||||||
|
global players_name_list
|
||||||
|
|
||||||
# Utilise get_or_create pour chercher un joueur existant ou en créer un nouveau avec les valeurs par défaut
|
# Utilise get_or_create pour chercher un joueur existant ou en créer un nouveau avec les valeurs par défaut
|
||||||
player, created = Player.objects.get_or_create(
|
print("Check player exist")
|
||||||
name=name,
|
if name_p1 in players_name_list:
|
||||||
defaults={
|
print(f"Player 1 {name_p1} exists")
|
||||||
'total_match': 0,
|
else :
|
||||||
'total_win': 0,
|
print(f"Player 1 {name_p1} does not exists")
|
||||||
'p_win': None,
|
player1 = Player(
|
||||||
'num_participated_tournaments': 0,
|
name = name_p1,
|
||||||
'num_won_tournaments': 0
|
total_match = 0,
|
||||||
}
|
total_win = 0,
|
||||||
)
|
p_win = 0,
|
||||||
if created:
|
num_participated_tournaments = 0,
|
||||||
print("Player created")
|
num_won_tournaments = 0)
|
||||||
else:
|
player1.save()
|
||||||
print("Player exists")
|
players_name_list.append(name_p1)
|
||||||
return player
|
print(f"Player {name_p1} creation done")
|
||||||
|
|
||||||
|
if name_p2 in players_name_list:
|
||||||
|
print(f"Player 2 {name_p2} exists")
|
||||||
|
else :
|
||||||
|
print(f"Player 2 {name_p2} does not exists")
|
||||||
|
player2 = Player(
|
||||||
|
name = name_p2,
|
||||||
|
total_match = 0,
|
||||||
|
total_win = 0,
|
||||||
|
p_win = 0,
|
||||||
|
num_participated_tournaments = 0,
|
||||||
|
num_won_tournaments = 0)
|
||||||
|
player2.save()
|
||||||
|
players_name_list.append(name_p2)
|
||||||
|
print(f"Player {name_p2} creation done")
|
||||||
|
|
||||||
|
#return player
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -58,6 +76,7 @@ def create_tournoi(name, nbr_player, date, winner):
|
|||||||
return tournoi
|
return tournoi
|
||||||
|
|
||||||
def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration, is_tournoi, tournoi):
|
def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration, is_tournoi, tournoi):
|
||||||
|
print("MATCH BEING REGISTERD")
|
||||||
match = Match(
|
match = Match(
|
||||||
player1=player1,
|
player1=player1,
|
||||||
player2=player2,
|
player2=player2,
|
||||||
@ -76,9 +95,14 @@ def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_
|
|||||||
match.winner = match.player2
|
match.winner = match.player2
|
||||||
else:
|
else:
|
||||||
match.winner = None
|
match.winner = None
|
||||||
|
|
||||||
|
|
||||||
|
print("MATCH SAVE IN DB")
|
||||||
match.save()
|
match.save()
|
||||||
return match
|
print("MATCH DONE")
|
||||||
|
#update_player_statistics(player1)
|
||||||
|
#update_player_statistics(player2)
|
||||||
|
#print("STAT DONE")
|
||||||
|
|
||||||
def update_player_statistics(player_name):
|
def update_player_statistics(player_name):
|
||||||
print("UPDATED DATA")
|
print("UPDATED DATA")
|
||||||
|
|||||||
@ -71,8 +71,8 @@ def match_list_json(request):
|
|||||||
matches = Match.objects.all()
|
matches = Match.objects.all()
|
||||||
data = {
|
data = {
|
||||||
'matches': list(matches.values(
|
'matches': list(matches.values(
|
||||||
'id', 'player1__name', 'player2__name', 'score_player1', 'score_player2',
|
'id', 'player1', 'player2', 'score_player1', 'score_player2',
|
||||||
'winner__name', 'nbr_ball_touch_p1', 'nbr_ball_touch_p2', 'duration', 'date',
|
'winner', 'nbr_ball_touch_p1', 'nbr_ball_touch_p2', 'duration', 'date',
|
||||||
'is_tournoi', 'tournoi__name'
|
'is_tournoi', 'tournoi__name'
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -109,11 +109,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const row = document.createElement('tr');
|
const row = document.createElement('tr');
|
||||||
row.innerHTML = `
|
row.innerHTML = `
|
||||||
<td>${match.id}</td>
|
<td>${match.id}</td>
|
||||||
<td>${match.player1__name}</td>
|
<td>${match.player1}</td>
|
||||||
<td>${match.player2__name}</td>
|
<td>${match.player2}</td>
|
||||||
<td>${match.score_player1}</td>
|
<td>${match.score_player1}</td>
|
||||||
<td>${match.score_player2}</td>
|
<td>${match.score_player2}</td>
|
||||||
<td>${match.winner__name}</td>
|
<td>${match.winner}</td>
|
||||||
<td>${match.nbr_ball_touch_p1}</td>
|
<td>${match.nbr_ball_touch_p1}</td>
|
||||||
<td>${match.nbr_ball_touch_p2}</td>
|
<td>${match.nbr_ball_touch_p2}</td>
|
||||||
<td>${match.duration}</td>
|
<td>${match.duration}</td>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user