starting the tournament code

This commit is contained in:
CHIBOUB Chakib
2024-08-27 18:46:56 +02:00
parent 6ac9629f6a
commit 697d8b5d0f
9 changed files with 116 additions and 53 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

@@ -22,7 +22,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
@@ -34,7 +35,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
@@ -53,9 +55,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()
@@ -66,9 +72,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:
@@ -92,21 +98,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()

View File

@@ -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()