Merge branch 'chaku' of github.com:AudebertAdrien/ft_transcendence into trash2

This commit is contained in:
Theouche
2024-08-28 13:18:16 +02:00
16 changed files with 258 additions and 202 deletions

View File

@@ -5,6 +5,7 @@ from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth.models import User
from channels.db import database_sync_to_async
from .matchmaking import match_maker
from .tournament import tournament_match_maker
class GameConsumer(AsyncWebsocketConsumer):
async def connect(self):
@@ -18,6 +19,8 @@ class GameConsumer(AsyncWebsocketConsumer):
await self.authenticate(data['token'])
elif data['type'] == 'authenticate2':
await self.authenticate2(data['token_1'], data['token_2'])
elif data['type'] == 'authenticate3':
await self.authenticate3(data['token'])
elif data['type'] == 'key_press':
if self.game:
await self.game.handle_key_press(self, data['key'])
@@ -74,10 +77,25 @@ class GameConsumer(AsyncWebsocketConsumer):
except User.DoesNotExist:
return None
async def authenticate3(self, token):
user = await self.get_user_from_token(token)
if user:
self.user = user
await self.send(text_data=json.dumps({'type': 'authenticated'}))
print(f"User {self.user} authenticated")
await self.join_tournament_waiting_room()
else:
await self.send(text_data=json.dumps({'type': 'error', 'message': 'Authentication failed'}))
print("Authentication failed")
async def join_tournament_waiting_room(self):
await tournament_match_maker.add_player(self)
async def disconnect(self, close_code):
if self.game:
await self.game.end_game(disconnected_player=self)
await match_maker.remove_player(self)
await tournament_match_maker.remove_player(self)
print(f"User {self.user.username if hasattr(self, 'user') else 'Unknown'} disconnected")
async def set_game(self, game):

View File

@@ -24,7 +24,8 @@ class Game:
'ball_position': {'x': 390, 'y': 190},
'ball_velocity': {'x': random.choice([-5, 5]), 'y': random.choice([-5, 5])},
'player1_score': 0,
'player2_score': 0
'player2_score': 0,
'game_text': ''
}
else:
self.botgame = player2 is None
@@ -36,7 +37,8 @@ class Game:
'ball_position': {'x': 390, 'y': 190},
'ball_velocity': {'x': random.choice([-5, 5]), 'y': random.choice([-5, 5])},
'player1_score': 0,
'player2_score': 0
'player2_score': 0,
'game-text': ''
}
self.speed = 1
self.game_loop_task = None
@@ -55,9 +57,13 @@ class Game:
async def game_loop(self):
print(" In the game loop..")
x = 0
while not self.ended:
if self.botgame:
await self.update_bot_position()
x += 1
if x == 60:
await self.update_bot_position()
x = 0
await self.handle_pad_movement()
await self.update_game_state()
await self.send_game_state()
@@ -68,9 +74,9 @@ class Game:
if self.game_state['player2_position'] < target_y < self.game_state['player2_position'] + 80:
pass
elif self.game_state['player2_position'] < target_y:
self.game_state['player2_position'] = min(self.game_state['player2_position'] + (5 * self.speed), 300)
self.game_state['player2_position'] = min(self.game_state['player2_position'] + (50 * self.speed), 300)
elif self.game_state['player2_position'] + 80 > target_y:
self.game_state['player2_position'] = max(self.game_state['player2_position'] - (5 * self.speed), 0)
self.game_state['player2_position'] = max(self.game_state['player2_position'] - (50 * self.speed), 0)
async def update_game_state(self):
if self.ended:
@@ -94,21 +100,18 @@ class Game:
self.game_state['ball_velocity']['x'] *= -1
self.bt2 += 1
self.update_ball_velocity()
# Check for scoring
#print(f"########### score user 1 {self.game_state['player1_score']} ###########")
#print(f"§§§§§§§§§§§ score user 2 {self.game_state['player2_score']} §§§§§§§§§§§")
# Check if some player won the game
if self.game_state['ball_position']['x'] <= 10:
self.game_state['player2_score'] += 1
if self.game_state['player2_score'] > 2:
print("Here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
self.game_state['game_text'] = f"{self.game_state['player2_name']} WINS!"
await self.send_game_state()
await self.end_game()
self.reset_ball()
elif self.game_state['ball_position']['x'] >= 790:
self.game_state['player1_score'] += 1
if self.game_state['player1_score'] > 2:
print("Here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
self.game_state['game_text'] = f"{self.game_state['player1_name']} WINS!"
await self.send_game_state()
await self.end_game()
self.reset_ball()
@@ -201,7 +204,8 @@ class Game:
'player': disconnected_name
})
if not self.botgame:
await remaining_player.send(message)
if not self.localgame:
await remaining_player.send(message)
# Notify both players that the game has ended
end_message = json.dumps({
'type': 'game_ended',

View File

@@ -40,7 +40,7 @@ class MatchMaker:
await asyncio.sleep(1)
self.timer += 1
# Waiting for more than 30s -> BOT game
if self.timer >= 30 and self.waiting_players:
if self.timer >= 15 and self.waiting_players:
player1 = self.waiting_players.pop(0)
print(f"*** MATCH FOUND: {player1.user.username} vs BOT")
self.botgame = True
@@ -110,6 +110,3 @@ class MatchMaker:
# Instance of the class
match_maker = MatchMaker()
# to get what you want use get_player_p_win(player_name) !! (voir utils.py)
#

View File

@@ -0,0 +1,10 @@
<!-- templates/tournament_waiting_room.html -->
<div class="tournament-waiting-room">
<h2>Tournament Waiting Room</h2>
<p>Players currently waiting: {{ players|length }}</p>
<ul>
{% for player in players %}
<li>{{ player }}</li>
{% endfor %}
</ul>
</div>

36
pong/game/tournament.py Normal file
View File

@@ -0,0 +1,36 @@
# /pong/game/tournament.py
import json
from django.template.loader import render_to_string
class TournamentMatchMaker:
def __init__(self):
self.waiting_players = []
async def add_player(self, player):
if player not in self.waiting_players:
self.waiting_players.append(player)
print(f"User {player.user.username} joins the TOURNAMENT WAITING ROOM")
await self.update_waiting_room()
async def remove_player(self, player):
if player in self.waiting_players:
self.waiting_players.remove(player)
await self.update_waiting_room()
async def update_waiting_room(self):
html = self.generate_waiting_room_html()
for player in self.waiting_players:
await player.send(json.dumps({
'type': 'update_waiting_room',
'html': html
}))
def generate_waiting_room_html(self):
context = {
'players': [player.user.username for player in self.waiting_players]
}
return render_to_string('pong/tournament_waiting_room.html', context)
# Instance of the class
tournament_match_maker = TournamentMatchMaker()

View File

@@ -22,6 +22,7 @@ from channels.db import database_sync_to_async
await update_player_statistics(p1)
print("############# END STAT P1")
await update_player_statistics(p2)
print("############# END STAT P2")
except Exception as e:
print(f"Error in endfortheouche: {e}")