From e88639bf880acbfa494111089139e63387c53d44 Mon Sep 17 00:00:00 2001 From: CHIBOUB Chakib Date: Mon, 16 Sep 2024 17:56:28 +0200 Subject: [PATCH] fixed game menu visual incongruencies --- makefile | 2 +- pong/game/game.py | 21 +++++---------------- pong/game/matchmaking.py | 2 +- pong/game/tournament.py | 13 ++++--------- pong/game/utils.py | 37 +++++++------------------------------ pong/game/views.py | 1 - pong/settings.py | 4 ++-- pong/static/burger.js | 9 +-------- pong/static/game.js | 21 ++++++++------------- pong/static/index.html | 12 ++++++------ pong/static/styles.css | 5 ++--- 11 files changed, 37 insertions(+), 90 deletions(-) diff --git a/makefile b/makefile index 3d815be..5c280d0 100644 --- a/makefile +++ b/makefile @@ -11,7 +11,7 @@ CONTAINER=$(c) up: down $(COMPOSE) build - $(COMPOSE) up -d $(CONTAINER) || true + $(COMPOSE) up $(CONTAINER) || true build: $(COMPOSE) build $(CONTAINER) diff --git a/pong/game/game.py b/pong/game/game.py index 52ef1e1..89e857b 100644 --- a/pong/game/game.py +++ b/pong/game/game.py @@ -65,8 +65,8 @@ class Game: if self.botgame: x += 1 if x == 60: - # Random BOT difficulty.. - steps = 60#random.randint(10, 60) + # Random BOT difficulty.. or not + steps = 60 # random.randint(10, 60) self.future_ball_position = await self.predict_ball_trajectory(steps) x = 0 if self.botgame: @@ -77,19 +77,16 @@ class Game: await asyncio.sleep(1/60) # Around 60 FPS async def update_bot_position(self): - #future_ball_position = self.predict_ball_trajectory() target_y = self.future_ball_position['y'] player2_position = self.game_state['player2_position'] - # Adjusts bot position based on expected ball position + # Adjusts BOT position based on expected ball position if player2_position < target_y < player2_position + 80: - pass #bot already placed + pass # BOT already placed elif player2_position < target_y: self.p2_mov = 1 - #self.game_state['player2_position'] = min(player2_position + (50 * self.speed), 300) elif player2_position + 80 > target_y: self.p2_mov = -1 - #self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0) async def predict_ball_trajectory(self, steps=60): future_x = self.game_state['ball_position']['x'] @@ -132,7 +129,7 @@ class Game: self.game_state['ball_velocity']['x'] *= -1 self.bt2 += 1 self.update_ball_velocity() - # Check if some player won the game + # Check if someone won the game (score: 3) if self.game_state['ball_position']['x'] <= 10: self.game_state['player2_score'] += 1 if self.game_state['player2_score'] > 2: @@ -218,8 +215,6 @@ class Game: async def end_game(self, disconnected_player=None): if not self.ended: self.ended = True - #if self.game_loop_task: - # self.game_loop_task.cancel() print(f"- Game #{self.game_id} ENDED --- ({self})") end_time = datetime.now() @@ -252,9 +247,3 @@ class Game: 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, avd, d) - - - - - - diff --git a/pong/game/matchmaking.py b/pong/game/matchmaking.py index 6382b95..f3eac70 100644 --- a/pong/game/matchmaking.py +++ b/pong/game/matchmaking.py @@ -41,7 +41,7 @@ class MatchMaker: await asyncio.sleep(1) self.timer += 1 # Waiting for more than 30s -> BOT game - if self.timer >= 15 and self.waiting_players: + if self.timer >= 30 and self.waiting_players: player1 = self.waiting_players.pop(0) print(f"*** MATCH FOUND: {player1.user.username} vs BOT") self.botgame = True diff --git a/pong/game/tournament.py b/pong/game/tournament.py index c057f3e..d858e4e 100644 --- a/pong/game/tournament.py +++ b/pong/game/tournament.py @@ -40,7 +40,7 @@ class TournamentMatchMaker: self.rounds = [] self.current_round = 0 self.games = 0 - self.tournament_state = "waiting" #Can be "waiting", "in_progress", or "ended" + self.tournament_state = "waiting" # Can be "waiting", "in_progress", or "ended" self.name = random.choice(TOURNAMENT_NAMES) self.final_name = "" self.tournoi_reg = None @@ -80,14 +80,11 @@ class TournamentMatchMaker: self.waiting_players.remove(player) await self.update_waiting_room() - # Tournament start method + # Tournament START method async def start_tournament(self): if len(self.waiting_players) < 3: return False random.shuffle(self.waiting_players) - '''if (len(self.waiting_players) % 2) != 0: - print("Adding a BYE to the tournament..") - await self.add_player(None)''' self.tournament_state = "in_progress" self.current_round = 0 len_tournament = await sync_to_async(getlen)() @@ -120,7 +117,6 @@ class TournamentMatchMaker: for i in range(0, len(players), 2): self.games += 1 if i + 1 < len(players): - # Create a new instance of TournamentMatch for this round match = TournamentMatch(self.games, players[i], players[i + 1], self) matches.append(match) else: @@ -176,11 +172,10 @@ 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() - await self.send_game_text(match.player1, "You lucky bastard!\n You got an auto-win!") + await self.send_game_text(match.player1, "You lucky bastard!\nYou got an auto-win!") async def send_game_text(self, player, text): message = json.dumps({ @@ -194,7 +189,6 @@ class TournamentMatchMaker: 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) return winners @@ -209,6 +203,7 @@ class TournamentMatchMaker: }) 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 98d53ae..14e2213 100644 --- a/pong/game/utils.py +++ b/pong/game/utils.py @@ -8,31 +8,21 @@ from datetime import timedelta from channels.db import database_sync_to_async def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament): - try: - player_1 = get_or_create_player(p1) - player_2 = get_or_create_player(p2) + player_1 = get_or_create_player(p1) + player_2 = get_or_create_player(p2) - 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) - print("and ADRIANO is the PEST") + create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament) - update_player_statistics(p1) - print("UPDATE PLAYER 1") - update_player_statistics(p2) - print("UPDATE PLAYER 2") - - except Exception as e: - print(f"Error in endfortheouche: {e}") + update_player_statistics(p1) + update_player_statistics(p2) def get_player_by_name(name): exists = Player.objects.filter(name=name).exists() return exists - def get_player(name): return Player.objects.get(name=name) - def get_or_create_player(name): player_exists = get_player_by_name(name) if not player_exists: @@ -42,7 +32,6 @@ def get_or_create_player(name): player = get_player(name) return player - def create_player( name, total_match=0, @@ -105,18 +94,14 @@ def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_ return match def update_player_statistics(player_name): - print(f"HERE for {player_name} §§§§§§§§§§§§") player = get_object_or_404(Player, name=player_name) - print(f"GET PLAYER {player.name} !!!!!!") matches_as_player1 = Match.objects.filter(player1=player) - #print(f"GET MATCH AS PLAYER 1 {matches_as_player1.player1.name} !!!!!!") matches_as_player2 = Match.objects.filter(player2=player) - #print(f"GET MATCH AS PLAYER 2 {matches_as_player2.player2.name} !!!!!!") total_match = matches_as_player1.count() + matches_as_player2.count() - # avoid dividing by 0 + # Avoid dividing by 0 if total_match == 0: player.total_match = total_match player.total_win = 0 @@ -184,24 +169,16 @@ def get_player_p_win(player_name): return player.p_win def create_tournament(name, nbr_player): - 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() \ No newline at end of file + return Tournoi.objects.count() diff --git a/pong/game/views.py b/pong/game/views.py index a09a6a5..0a31ed4 100644 --- a/pong/game/views.py +++ b/pong/game/views.py @@ -9,7 +9,6 @@ from django.contrib.auth.models import User from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets - import json import uuid diff --git a/pong/settings.py b/pong/settings.py index 4028b33..170a945 100644 --- a/pong/settings.py +++ b/pong/settings.py @@ -138,7 +138,7 @@ CHANNEL_LAYERS = { }, } -LOGGING = { +'''LOGGING = { 'version': 1, # Django requires this key 'disable_existing_loggers': False, # Keep Django's default loggers 'formatters': { @@ -161,7 +161,7 @@ LOGGING = { 'propagate': False, # Prevents log propagation to other loggers }, }, -} +}''' """ LOGGING = { diff --git a/pong/static/burger.js b/pong/static/burger.js index ca45088..eb80c9e 100644 --- a/pong/static/burger.js +++ b/pong/static/burger.js @@ -8,8 +8,6 @@ document.addEventListener('DOMContentLoaded', () => { const tournoiList = document.getElementById('tournoi-list'); const blockchainList = document.getElementById('blockchain-list'); - const logo = document.querySelector('.logo'); - menuButton.addEventListener('click', toggleMenu); function toggleMenu() { @@ -27,7 +25,6 @@ document.addEventListener('DOMContentLoaded', () => { if (matchList) matchList.style.display = 'none'; if (tournoiList) tournoiList.style.display = 'none'; if (blockchainList) blockchainList.style.display = 'none'; - logo.style.display = 'block'; } const links = document.querySelectorAll('#dropdown-menu a'); @@ -42,7 +39,6 @@ document.addEventListener('DOMContentLoaded', () => { function showTable(tableId) { hideAllTables(); - logo.style.display = 'none'; if (tableId === 'player-list') { playerList.style.display = 'block'; @@ -262,9 +258,6 @@ document.addEventListener('DOMContentLoaded', () => { return ; } - if (logo.style.display === 'block'){ - logo.style.display = 'none'; - } const rows = document.querySelectorAll('#player-list tbody tr'); const playerNames = []; const totalMatches = []; @@ -401,4 +394,4 @@ document.addEventListener('DOMContentLoaded', () => { return color; } -}); \ No newline at end of file +}); diff --git a/pong/static/game.js b/pong/static/game.js index 4680c5b..6bf91ff 100644 --- a/pong/static/game.js +++ b/pong/static/game.js @@ -30,6 +30,8 @@ document.addEventListener('DOMContentLoaded', () => { const gameContainer = document.getElementById('game1'); const tournamentContainer = document.getElementById('tournament-bracket'); + const burgerMenu = document.querySelector('.navbar'); + const pongElements = document.getElementById('pong-elements'); const logo = document.querySelector('.logo'); @@ -161,6 +163,9 @@ document.addEventListener('DOMContentLoaded', () => { if (result) { loginForm.style.display = 'none'; document.getElementById("post-form-buttons").style.display = 'block'; + burgerMenu.style.display = 'block'; + logo.style.display = 'none'; + pongElements.style.display = 'none'; } else { alert('Authentication failed. Please try again.'); } @@ -325,8 +330,6 @@ document.addEventListener('DOMContentLoaded', () => { player2_name: nickname2 }; gameContainer.style.display = 'flex'; - logo.style.display = 'none'; - pongElements.style.display = 'none'; formBlock.style.display = 'none'; startWebSocketConnection(token, 2); } @@ -336,8 +339,6 @@ document.addEventListener('DOMContentLoaded', () => { type: 'quick' } gameContainer.style.display = 'flex'; - logo.style.display = 'none'; - pongElements.style.display = 'none'; formBlock.style.display = 'none'; document.getElementById('player1-name').textContent = "player 1"; document.getElementById('player2-name').textContent = "player 2"; @@ -353,8 +354,6 @@ document.addEventListener('DOMContentLoaded', () => { type: 'tournoi' } tournamentContainer.style.display = 'flex'; - logo.style.display = 'none'; - pongElements.style.display = 'none'; formBlock.style.display = 'none'; startWebSocketConnection(token, 42); } @@ -398,7 +397,7 @@ document.addEventListener('DOMContentLoaded', () => { console.error(data.message); } else if (data.type === 'update_tournament_waiting_room') { // Update the HTML content of the tournament bracket - document.getElementById('tournament-bracket').innerHTML = data.html; + tournamentContainer.innerHTML = data.html; // Reattach the event listener to the "Start Tournament" button const startButton = document.getElementById('start-tournament-btn'); if (startButton) { @@ -413,7 +412,7 @@ document.addEventListener('DOMContentLoaded', () => { } } else if (data.type === 'update_brackets') { // Update the HTML content of the tournament bracket - document.getElementById('tournament-bracket').innerHTML = data.html; + tournamentContainer.innerHTML = data.html; } else if (data.type === 'tournament_end') { console.log('Tournament ended, the winner is:', data.winner); } else { @@ -487,12 +486,8 @@ document.addEventListener('DOMContentLoaded', () => { homeButton.addEventListener('click', () => { gameContainer.style.display = 'none'; gameControls.style.display = 'none'; - - logo.style.display = 'block' - formBlock.style.display = 'block'; - postFormButtons.style.display = 'flex'; - + postFormButtons.style.display = 'block'; setupFirstPlayer(); }); diff --git a/pong/static/index.html b/pong/static/index.html index 3588d07..954f91d 100644 --- a/pong/static/index.html +++ b/pong/static/index.html @@ -92,7 +92,7 @@ -