diff --git a/docker-compose.yml_old b/docker-compose.yml_old new file mode 100644 index 0000000..aa21870 --- /dev/null +++ b/docker-compose.yml_old @@ -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 diff --git a/logs/django.log b/logs/django.log index 444904d..7683829 100644 --- a/logs/django.log +++ b/logs/django.log @@ -7,3 +7,4 @@ {"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": ""} {"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": ""} {"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": ""} +{"message": "Not Found: /favicon.ico", "taskName": null, "status_code": 404, "request": ""} diff --git a/pong/game/game.py b/pong/game/game.py index 2235970..a5c9320 100644 --- a/pong/game/game.py +++ b/pong/game/game.py @@ -4,8 +4,9 @@ import json import asyncio import random 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 .models import Tournoi class Game: def __init__(self, game_id, player1, player2, localgame): @@ -27,9 +28,10 @@ class Game: 'game_text': '' } 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 = { - 'player1_name': player1.user.username, + 'player1_name': player1.user.username if player1 else 'BOT', 'player2_name': player2.user.username if player2 else 'BOT', 'player1_position': 150, 'player2_position': 150, @@ -241,6 +243,11 @@ class Game: if not self.botgame: if not self.localgame: 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.bt1, self.bt2, duration, False, None) diff --git a/pong/game/templates/pong/tournament_brackets.html b/pong/game/templates/pong/tournament_brackets.html index f7f0999..ca65553 100644 --- a/pong/game/templates/pong/tournament_brackets.html +++ b/pong/game/templates/pong/tournament_brackets.html @@ -41,14 +41,20 @@
+ {% for round in tournament_rounds %}
+ {% for match in round %}
+ {{ match.player1 }}
+ {{ match.player2|default:"BYE" }}
+ {% endfor %}
+ {% endfor %}
\ No newline at end of file diff --git a/pong/game/tournament.py b/pong/game/tournament.py index 7a581e2..b0c6c1b 100644 --- a/pong/game/tournament.py +++ b/pong/game/tournament.py @@ -7,7 +7,7 @@ import random from .matchmaking import match_maker from .game import Game from .models import Tournoi -from .utils import create_tournament +from .utils import create_tournament, update_tournament, getlen from asgiref.sync import sync_to_async @@ -17,18 +17,18 @@ TOURNAMENT_NAMES = [ "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): def __init__(self, game_id, player1, player2, tournament): # Initialize the parent Game class with the provided parameters super().__init__(game_id, player1, player2, False) # Store the current game instance in active games 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 self.tournament = tournament @@ -37,7 +37,8 @@ class TournamentMatch(Game): await super().end_game(disconnected_player) # Handle the end of the match in the tournament context 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: def __init__(self): @@ -46,13 +47,18 @@ class TournamentMatchMaker: self.rounds = [] self.current_round = 0 self.games = 0 + self.tournament_state = "waiting" #Can be "waiting", "in_progress", or "ended" 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): if self.tournament_state == "waiting" and player not in self.waiting_players: 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() async def update_waiting_room(self): @@ -65,15 +71,16 @@ class TournamentMatchMaker: def generate_waiting_room_html(self): 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, '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) 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): if player in self.waiting_players: @@ -82,12 +89,17 @@ class TournamentMatchMaker: # Tournament start method async def start_tournament(self): + 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" random.shuffle(self.waiting_players) 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() return True @@ -120,13 +132,15 @@ class TournamentMatchMaker: matches.append(match) else: # 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) # 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): - await players[i + 1].set_game(match) + if players[i + 1]: + await players[i + 1].set_game(match) self.rounds.append(matches) self.matches.extend(matches) @@ -149,8 +163,8 @@ class TournamentMatchMaker: return [ [ { - 'player1': match.player1.user.username if match.player1 else 'BOT', - 'player2': match.player2.user.username if match.player2 else 'BOT', + 'player1': match.player1.user.username if match.player1 else 'BYE', + '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, 'score1': match.game_state['player1_score'], 'score2': match.game_state['player2_score'] @@ -169,18 +183,18 @@ class TournamentMatchMaker: elif match.player1: # Handle BYE match 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['player2_score'] = 0 await match.end_game() - #asyncio.create_task(match.start_game()) def get_round_winners(self): winners = [] for match in self.rounds[-1]: if match.ended: winner = match.player1 if match.game_state['player1_score'] > match.game_state['player2_score'] else match.player2 - if winner: - winners.append(winner) + #if winner: + winners.append(winner) return winners async def end_tournament(self, winner): @@ -192,6 +206,8 @@ class TournamentMatchMaker: 'type': 'tournament_end', 'winner': winner_username }) + + await sync_to_async(update_tournament)(self.final_name, winner_username) # Reset tournament state self.waiting_players = [] self.matches = [] diff --git a/pong/game/utils.py b/pong/game/utils.py index c911138..16921d0 100644 --- a/pong/game/utils.py +++ b/pong/game/utils.py @@ -173,9 +173,24 @@ def get_player_p_win(player_name): return player.p_win def create_tournament(name, nbr_player): - print("here !!!") + print("tournoi created!!!") tournoi=Tournoi(name=name, nbr_player=nbr_player, winner=None) 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() diff --git a/pong/static/burger.js b/pong/static/burger.js index a98343c..aa2139a 100644 --- a/pong/static/burger.js +++ b/pong/static/burger.js @@ -103,10 +103,10 @@ document.addEventListener('DOMContentLoaded', () => { console.log('Displaying matches:'); const matchListBody = document.querySelector('#match-list tbody'); matchListBody.innerHTML = ''; + const row = document.createElement('tr'); if (matches.length != 0) { matches.forEach(match => { - const row = document.createElement('tr'); row.innerHTML = ` ${match.id} ${match.player1__name} @@ -135,10 +135,10 @@ document.addEventListener('DOMContentLoaded', () => { console.log('Displaying players:'); const playersListBody = document.querySelector('#player-list tbody'); playersListBody.innerHTML = ''; + const row = document.createElement('tr'); if (players.length != 0) { players.forEach(player => { - const row = document.createElement('tr'); row.innerHTML = ` ${player.id} ${player.name} @@ -168,16 +168,16 @@ document.addEventListener('DOMContentLoaded', () => { console.log('Displaying tournois:'); const tournoisListBody = document.querySelector('#tournoi-list tbody'); tournoisListBody.innerHTML = ''; + const row = document.createElement('tr'); if (tournois.length != 0) { tournois.forEach(tournoi => { - const row = document.createElement('tr'); row.innerHTML = ` ${tournoi.id} ${tournoi.name} ${tournoi.nbr_player} ${tournoi.date} - ${tournoi.winner.name} + ${tournoi.winner ? tournoi.winner.name : 'None'} `; tournoisListBody.appendChild(row); });