mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2025-12-18 15:07:49 +01:00
tournoi register
This commit is contained in:
commit
eaf30dc043
75
docker-compose.yml_old
Normal file
75
docker-compose.yml_old
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
services:
|
||||||
|
backend:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
image: backend
|
||||||
|
container_name: backend
|
||||||
|
restart: always
|
||||||
|
command: /bin/sh -c "sleep 5 &&
|
||||||
|
venv/bin/python manage.py makemigrations --noinput &&
|
||||||
|
venv/bin/python manage.py migrate --noinput &&
|
||||||
|
venv/bin/python manage.py collectstatic --noinput &&
|
||||||
|
venv/bin/daphne -b 0.0.0.0 -p 8080 pong.asgi:application"
|
||||||
|
volumes:
|
||||||
|
- pong:/transcendence/pong
|
||||||
|
- pong_django_logs:/transcendence/logs
|
||||||
|
ports:
|
||||||
|
- 8080:8080
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
environment:
|
||||||
|
DB_HOST: db
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_NAME: ${POSTGRES_DB}
|
||||||
|
DB_USER: ${POSTGRES_USER}
|
||||||
|
DB_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl", "http://localhost:8080"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
start_period: 10s
|
||||||
|
|
||||||
|
db:
|
||||||
|
image: postgres:latest
|
||||||
|
container_name: postgres
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
- pong_pg_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pong:
|
||||||
|
driver: local
|
||||||
|
driver_opts:
|
||||||
|
type: none
|
||||||
|
device: ${PROJECT_PATH}
|
||||||
|
o: bind
|
||||||
|
pong_django_logs:
|
||||||
|
driver: local
|
||||||
|
driver_opts:
|
||||||
|
type: none
|
||||||
|
device: ${DJANGO_LOGS}
|
||||||
|
o: bind
|
||||||
|
pong_pg_data:
|
||||||
|
driver: local
|
||||||
|
|
||||||
|
networks:
|
||||||
|
app-network:
|
||||||
|
name: app-network
|
||||||
|
driver: bridge
|
||||||
@ -7,3 +7,4 @@
|
|||||||
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
||||||
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
||||||
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
||||||
|
{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": "<ASGIRequest: GET '/favicon.ico'>"}
|
||||||
|
|||||||
@ -4,8 +4,9 @@ import json
|
|||||||
import asyncio
|
import asyncio
|
||||||
import random
|
import random
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from .utils import handle_game_data
|
from .utils import handle_game_data, getlen
|
||||||
from asgiref.sync import sync_to_async
|
from asgiref.sync import sync_to_async
|
||||||
|
from .models import Tournoi
|
||||||
|
|
||||||
class Game:
|
class Game:
|
||||||
def __init__(self, game_id, player1, player2, localgame):
|
def __init__(self, game_id, player1, player2, localgame):
|
||||||
@ -27,9 +28,10 @@ class Game:
|
|||||||
'game_text': ''
|
'game_text': ''
|
||||||
}
|
}
|
||||||
else:
|
else:
|
||||||
self.botgame = player2 is None
|
# Set botgame to True if either player1 or player2 is None
|
||||||
|
self.botgame = player1 is None or player2 is None
|
||||||
self.game_state = {
|
self.game_state = {
|
||||||
'player1_name': player1.user.username,
|
'player1_name': player1.user.username if player1 else 'BOT',
|
||||||
'player2_name': player2.user.username if player2 else 'BOT',
|
'player2_name': player2.user.username if player2 else 'BOT',
|
||||||
'player1_position': 150,
|
'player1_position': 150,
|
||||||
'player2_position': 150,
|
'player2_position': 150,
|
||||||
@ -241,6 +243,11 @@ class Game:
|
|||||||
if not self.botgame:
|
if not self.botgame:
|
||||||
if not self.localgame:
|
if not self.localgame:
|
||||||
await self.player2.send(end_message)
|
await self.player2.send(end_message)
|
||||||
await sync_to_async(handle_game_data)(self.game_state['player1_name'], self.game_state['player2_name'],
|
if hasattr(self, 'tournament'):
|
||||||
|
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)
|
||||||
|
else:
|
||||||
|
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.game_state['player1_score'], self.game_state['player2_score'],
|
||||||
self.bt1, self.bt2, duration, False, None)
|
self.bt1, self.bt2, duration, False, None)
|
||||||
|
|||||||
@ -41,14 +41,20 @@
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="tournament-bracket">
|
<div class="tournament-bracket">
|
||||||
|
{% for round in tournament_rounds %}
|
||||||
<div class="round">
|
<div class="round">
|
||||||
|
{% for match in round %}
|
||||||
<div class="match">
|
<div class="match">
|
||||||
<div class="player {% if match.winner == match.player1 %}winner{% endif %}">
|
<div class="player {% if match.winner == match.player1 %}winner{% endif %}">
|
||||||
|
{{ match.player1 }}
|
||||||
</div>
|
</div>
|
||||||
<div class="player {% if match.winner == match.player2 %}winner{% endif %}">
|
<div class="player {% if match.winner == match.player2 %}winner{% endif %}">
|
||||||
|
{{ match.player2|default:"BYE" }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
|
{% endfor %}
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@ -7,7 +7,7 @@ import random
|
|||||||
from .matchmaking import match_maker
|
from .matchmaking import match_maker
|
||||||
from .game import Game
|
from .game import Game
|
||||||
from .models import Tournoi
|
from .models import Tournoi
|
||||||
from .utils import create_tournament
|
from .utils import create_tournament, update_tournament, getlen
|
||||||
from asgiref.sync import sync_to_async
|
from asgiref.sync import sync_to_async
|
||||||
|
|
||||||
|
|
||||||
@ -17,18 +17,18 @@ TOURNAMENT_NAMES = [
|
|||||||
"Shibuya incident", "Cunning Game", "Elite of the Stars"
|
"Shibuya incident", "Cunning Game", "Elite of the Stars"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
TOURNAMENT_NAMES = [
|
||||||
|
"Champion's Clash", "Ultimate Showdown", "Battle Royale",
|
||||||
|
"Victory's Cup", "Legends Tournament", "Elite Series", "Clash of 42",
|
||||||
|
"Shibuya Incident", "Cunning Game", "Elite of the Stars", "Chaku's Disciples"
|
||||||
|
]
|
||||||
|
|
||||||
class TournamentMatch(Game):
|
class TournamentMatch(Game):
|
||||||
def __init__(self, game_id, player1, player2, tournament):
|
def __init__(self, game_id, player1, player2, tournament):
|
||||||
# Initialize the parent Game class with the provided parameters
|
# Initialize the parent Game class with the provided parameters
|
||||||
super().__init__(game_id, player1, player2, False)
|
super().__init__(game_id, player1, player2, False)
|
||||||
# Store the current game instance in active games
|
# Store the current game instance in active games
|
||||||
match_maker.active_games[game_id] = self
|
match_maker.active_games[game_id] = self
|
||||||
# Set the game for the players
|
|
||||||
'''player1.set_game(self)
|
|
||||||
print(f"{player1.user.username} set to game #{self}")
|
|
||||||
if player2:
|
|
||||||
player2.set_game(self)
|
|
||||||
print(f"{player2.user.username} set to game #{self}")'''
|
|
||||||
# Store the tournament instance
|
# Store the tournament instance
|
||||||
self.tournament = tournament
|
self.tournament = tournament
|
||||||
|
|
||||||
@ -37,7 +37,8 @@ class TournamentMatch(Game):
|
|||||||
await super().end_game(disconnected_player)
|
await super().end_game(disconnected_player)
|
||||||
# Handle the end of the match in the tournament context
|
# Handle the end of the match in the tournament context
|
||||||
await self.tournament.handle_match_end(self)
|
await self.tournament.handle_match_end(self)
|
||||||
del match_maker.active_games[self.game_id]
|
if self.game_id in match_maker.active_games:
|
||||||
|
del match_maker.active_games[self.game_id]
|
||||||
|
|
||||||
class TournamentMatchMaker:
|
class TournamentMatchMaker:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -46,13 +47,18 @@ class TournamentMatchMaker:
|
|||||||
self.rounds = []
|
self.rounds = []
|
||||||
self.current_round = 0
|
self.current_round = 0
|
||||||
self.games = 0
|
self.games = 0
|
||||||
|
self.tournament_state = "waiting" #Can be "waiting", "in_progress", or "ended"
|
||||||
self.name = random.choice(TOURNAMENT_NAMES)
|
self.name = random.choice(TOURNAMENT_NAMES)
|
||||||
self.tournament_state = "waiting" # Can be "waiting", "in_progress", or "ended"
|
self.final_name = ""
|
||||||
|
self.tournoi_reg = None
|
||||||
|
|
||||||
async def add_player(self, player):
|
async def add_player(self, player):
|
||||||
if self.tournament_state == "waiting" and player not in self.waiting_players:
|
if self.tournament_state == "waiting" and player not in self.waiting_players:
|
||||||
self.waiting_players.append(player)
|
self.waiting_players.append(player)
|
||||||
print(f"User {player.user.username} joins the TOURNAMENT WAITING ROOM")
|
if player:
|
||||||
|
print(f"User {player.user.username} joins the TOURNAMENT WAITING ROOM")
|
||||||
|
else:
|
||||||
|
print("BOT joins the TOURNAMENT WAITING ROOM")
|
||||||
await self.update_waiting_room()
|
await self.update_waiting_room()
|
||||||
|
|
||||||
async def update_waiting_room(self):
|
async def update_waiting_room(self):
|
||||||
@ -65,15 +71,16 @@ class TournamentMatchMaker:
|
|||||||
|
|
||||||
def generate_waiting_room_html(self):
|
def generate_waiting_room_html(self):
|
||||||
context = {
|
context = {
|
||||||
'players': [player.user.username for player in self.waiting_players],
|
'players': [player.user.username if player else 'BYE' for player in self.waiting_players],
|
||||||
'tournament_state': self.tournament_state,
|
'tournament_state': self.tournament_state,
|
||||||
'players_count': len(self.waiting_players),
|
'players_count': len(self.waiting_players),
|
||||||
'min_players_to_start': 2 # You can adjust this number as needed
|
'min_players_to_start': 3 # You can adjust this number as needed
|
||||||
}
|
}
|
||||||
return render_to_string('pong/tournament_waiting_room.html', context)
|
return render_to_string('pong/tournament_waiting_room.html', context)
|
||||||
|
|
||||||
async def send_to_player(self, player, data):
|
async def send_to_player(self, player, data):
|
||||||
await player.send(json.dumps(data))
|
if player:
|
||||||
|
await player.send(json.dumps(data))
|
||||||
|
|
||||||
async def remove_player(self, player):
|
async def remove_player(self, player):
|
||||||
if player in self.waiting_players:
|
if player in self.waiting_players:
|
||||||
@ -82,12 +89,17 @@ class TournamentMatchMaker:
|
|||||||
|
|
||||||
# Tournament start method
|
# Tournament start method
|
||||||
async def start_tournament(self):
|
async def start_tournament(self):
|
||||||
|
|
||||||
if len(self.waiting_players) < 2:
|
if len(self.waiting_players) < 2:
|
||||||
return False
|
return False
|
||||||
|
if len(self.waiting_players) % 2 == 0:
|
||||||
|
await self.add_player(None)
|
||||||
self.tournament_state = "in_progress"
|
self.tournament_state = "in_progress"
|
||||||
random.shuffle(self.waiting_players)
|
random.shuffle(self.waiting_players)
|
||||||
self.current_round = 0
|
self.current_round = 0
|
||||||
#await sync_to_async(create_tournament)(self.name, len(self.waiting_players))
|
len_tournament = await sync_to_async(getlen)()
|
||||||
|
self.final_name = self.name + " #" + str(len_tournament + 1)
|
||||||
|
self.tournoi_reg = await sync_to_async(create_tournament)(self.final_name, len(self.waiting_players))
|
||||||
await self.advance_tournament()
|
await self.advance_tournament()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@ -120,13 +132,15 @@ class TournamentMatchMaker:
|
|||||||
matches.append(match)
|
matches.append(match)
|
||||||
else:
|
else:
|
||||||
# Create a BYE match where the second player is None
|
# Create a BYE match where the second player is None
|
||||||
match = TournamentMatch(self.games, players[i], None, self) # BYE match
|
match = TournamentMatch(self.games, players[i], None, self) # BYE match
|
||||||
matches.append(match)
|
matches.append(match)
|
||||||
|
|
||||||
# Assign the new match instance to the players
|
# Assign the new match instance to the players
|
||||||
await players[i].set_game(match)
|
if players[i]:
|
||||||
|
await players[i].set_game(match)
|
||||||
if i + 1 < len(players):
|
if i + 1 < len(players):
|
||||||
await players[i + 1].set_game(match)
|
if players[i + 1]:
|
||||||
|
await players[i + 1].set_game(match)
|
||||||
|
|
||||||
self.rounds.append(matches)
|
self.rounds.append(matches)
|
||||||
self.matches.extend(matches)
|
self.matches.extend(matches)
|
||||||
@ -149,8 +163,8 @@ class TournamentMatchMaker:
|
|||||||
return [
|
return [
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
'player1': match.player1.user.username if match.player1 else 'BOT',
|
'player1': match.player1.user.username if match.player1 else 'BYE',
|
||||||
'player2': match.player2.user.username if match.player2 else 'BOT',
|
'player2': match.player2.user.username if match.player2 else 'BYE',
|
||||||
'winner': match.game_state['player1_name'] if match.game_state['player1_score'] > match.game_state['player2_score'] else match.game_state['player2_name'] if match.ended else None,
|
'winner': match.game_state['player1_name'] if match.game_state['player1_score'] > match.game_state['player2_score'] else match.game_state['player2_name'] if match.ended else None,
|
||||||
'score1': match.game_state['player1_score'],
|
'score1': match.game_state['player1_score'],
|
||||||
'score2': match.game_state['player2_score']
|
'score2': match.game_state['player2_score']
|
||||||
@ -169,18 +183,18 @@ class TournamentMatchMaker:
|
|||||||
elif match.player1:
|
elif match.player1:
|
||||||
# Handle BYE match
|
# Handle BYE match
|
||||||
await match_maker.notify_players(match.player1, match.player2, match.game_id, False)
|
await match_maker.notify_players(match.player1, match.player2, match.game_id, False)
|
||||||
|
#asyncio.create_task(match.start_game())
|
||||||
match.game_state['player1_score'] = 3
|
match.game_state['player1_score'] = 3
|
||||||
match.game_state['player2_score'] = 0
|
match.game_state['player2_score'] = 0
|
||||||
await match.end_game()
|
await match.end_game()
|
||||||
#asyncio.create_task(match.start_game())
|
|
||||||
|
|
||||||
def get_round_winners(self):
|
def get_round_winners(self):
|
||||||
winners = []
|
winners = []
|
||||||
for match in self.rounds[-1]:
|
for match in self.rounds[-1]:
|
||||||
if match.ended:
|
if match.ended:
|
||||||
winner = match.player1 if match.game_state['player1_score'] > match.game_state['player2_score'] else match.player2
|
winner = match.player1 if match.game_state['player1_score'] > match.game_state['player2_score'] else match.player2
|
||||||
if winner:
|
#if winner:
|
||||||
winners.append(winner)
|
winners.append(winner)
|
||||||
return winners
|
return winners
|
||||||
|
|
||||||
async def end_tournament(self, winner):
|
async def end_tournament(self, winner):
|
||||||
@ -192,6 +206,8 @@ class TournamentMatchMaker:
|
|||||||
'type': 'tournament_end',
|
'type': 'tournament_end',
|
||||||
'winner': winner_username
|
'winner': winner_username
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await sync_to_async(update_tournament)(self.final_name, winner_username)
|
||||||
# Reset tournament state
|
# Reset tournament state
|
||||||
self.waiting_players = []
|
self.waiting_players = []
|
||||||
self.matches = []
|
self.matches = []
|
||||||
|
|||||||
@ -173,9 +173,24 @@ def get_player_p_win(player_name):
|
|||||||
return player.p_win
|
return player.p_win
|
||||||
|
|
||||||
def create_tournament(name, nbr_player):
|
def create_tournament(name, nbr_player):
|
||||||
print("here !!!")
|
print("tournoi created!!!")
|
||||||
tournoi=Tournoi(name=name, nbr_player=nbr_player, winner=None)
|
tournoi=Tournoi(name=name, nbr_player=nbr_player, winner=None)
|
||||||
tournoi.save()
|
tournoi.save()
|
||||||
|
print(f"tournoi name : {tournoi.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
|
||||||
|
return tournoi
|
||||||
|
|
||||||
|
def update_tournament(name_tournoi, winner_name):
|
||||||
|
tournoi = get_object_or_404(Tournoi, name=name_tournoi)
|
||||||
|
winner_p = get_object_or_404(Player, name=winner_name)
|
||||||
|
print(f"in update tourna - tournoi name : {tournoi.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
|
||||||
|
print(f"in update tourna - winner is : {winner_p.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
|
||||||
|
|
||||||
|
tournoi.winner = winner_p
|
||||||
|
print(f"in update tourna - TOURNOI winner is : {tournoi.winner.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
|
||||||
|
tournoi.save()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def getlen():
|
||||||
|
return Tournoi.objects.count()
|
||||||
|
|||||||
@ -103,10 +103,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
console.log('Displaying matches:');
|
console.log('Displaying matches:');
|
||||||
const matchListBody = document.querySelector('#match-list tbody');
|
const matchListBody = document.querySelector('#match-list tbody');
|
||||||
matchListBody.innerHTML = '';
|
matchListBody.innerHTML = '';
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
|
||||||
if (matches.length != 0) {
|
if (matches.length != 0) {
|
||||||
matches.forEach(match => {
|
matches.forEach(match => {
|
||||||
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__name}</td>
|
||||||
@ -135,10 +135,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
console.log('Displaying players:');
|
console.log('Displaying players:');
|
||||||
const playersListBody = document.querySelector('#player-list tbody');
|
const playersListBody = document.querySelector('#player-list tbody');
|
||||||
playersListBody.innerHTML = '';
|
playersListBody.innerHTML = '';
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
|
||||||
if (players.length != 0) {
|
if (players.length != 0) {
|
||||||
players.forEach(player => {
|
players.forEach(player => {
|
||||||
const row = document.createElement('tr');
|
|
||||||
row.innerHTML = `
|
row.innerHTML = `
|
||||||
<td>${player.id}</td>
|
<td>${player.id}</td>
|
||||||
<td>${player.name}</td>
|
<td>${player.name}</td>
|
||||||
@ -168,16 +168,16 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
console.log('Displaying tournois:');
|
console.log('Displaying tournois:');
|
||||||
const tournoisListBody = document.querySelector('#tournoi-list tbody');
|
const tournoisListBody = document.querySelector('#tournoi-list tbody');
|
||||||
tournoisListBody.innerHTML = '';
|
tournoisListBody.innerHTML = '';
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
|
||||||
if (tournois.length != 0) {
|
if (tournois.length != 0) {
|
||||||
tournois.forEach(tournoi => {
|
tournois.forEach(tournoi => {
|
||||||
const row = document.createElement('tr');
|
|
||||||
row.innerHTML = `
|
row.innerHTML = `
|
||||||
<td>${tournoi.id}</td>
|
<td>${tournoi.id}</td>
|
||||||
<td>${tournoi.name}</td>
|
<td>${tournoi.name}</td>
|
||||||
<td>${tournoi.nbr_player}</td>
|
<td>${tournoi.nbr_player}</td>
|
||||||
<td>${tournoi.date}</td>
|
<td>${tournoi.date}</td>
|
||||||
<td>${tournoi.winner.name}</td>
|
<td>${tournoi.winner ? tournoi.winner.name : 'None'}</td>
|
||||||
`;
|
`;
|
||||||
tournoisListBody.appendChild(row);
|
tournoisListBody.appendChild(row);
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user