tournament WORKING and bot AI fixed somehow

This commit is contained in:
CHIBOUB Chakib 2024-09-09 21:34:35 +02:00
parent 878cf92bbb
commit 3e0c3aa3bb
6 changed files with 39 additions and 25 deletions

View File

@ -6,6 +6,7 @@ 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
import asyncio
class GameConsumer(AsyncWebsocketConsumer):
async def connect(self):
@ -24,11 +25,10 @@ class GameConsumer(AsyncWebsocketConsumer):
elif data['type'] == 'key_press':
if self.game:
await self.game.handle_key_press(self, data['key'])
else:
await match_maker.handle_key_press(self, data['key'])
elif data['type'] == 'start_tournament':
print("Start TOURNAMENT received..")
await tournament_match_maker.start_tournament()
print(f"Start TOURNAMENT received by {self.user}")
# Run the tournament in the background
asyncio.create_task(tournament_match_maker.start_tournament())
async def authenticate(self, token):
user = await self.get_user_from_token(token)
@ -102,4 +102,5 @@ class GameConsumer(AsyncWebsocketConsumer):
print(f"User {self.user.username if hasattr(self, 'user') else 'Unknown'} disconnected")
async def set_game(self, game):
print(f"({self.user}) Game set to: {game}")
self.game = game

View File

@ -49,7 +49,7 @@ class Game:
self.start_time = datetime.now()
async def start_game(self):
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']})")
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']}) --- ({self})")
self.game_loop_task = asyncio.create_task(self.game_loop())
print(f" Begin MATCH at: {self.start_time}")
@ -77,8 +77,10 @@ class Game:
if player2_position < target_y < player2_position + 80:
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)
def predict_ball_trajectory(self, steps=60):
@ -90,10 +92,16 @@ class Game:
for _ in range(steps):
future_x += velocity_x
if future_x <= 10:
future_x = 10
velocity_x = -velocity_x
elif future_x >= 790:
future_x = 790
else:
future_y += velocity_y
# Dealing with bounces off walls
if future_y <= 0 or future_y >= 300:
if future_y <= 10 or future_y >= 390:
velocity_y = -velocity_y # Reverse the direction of vertical movement
return {'x': future_x, 'y': future_y}
@ -208,7 +216,7 @@ class Game:
self.ended = True
if self.game_loop_task:
self.game_loop_task.cancel()
print(f"- Game #{self.game_id} ENDED")
print(f"- Game #{self.game_id} ENDED --- ({self})")
end_time = datetime.now()
duration = (end_time - self.start_time).total_seconds() / 60

View File

@ -26,6 +26,7 @@ class MatchMaker:
for game in self.active_games.values():
if player in [game.player1, game.player2]:
await game.end_game(disconnected_player=player)
if game.game_id in self.active_games:
del self.active_games[game.game_id]
break
@ -102,11 +103,5 @@ class MatchMaker:
'player2': 'BOT'
}))
async def handle_key_press(self, player, key):
for game in self.active_games.values():
if player in [game.player1, game.player2]:
await game.handle_key_press(player, key)
break
# Instance of the class
match_maker = MatchMaker()

View File

@ -14,9 +14,11 @@ class TournamentMatch(Game):
# 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)
'''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
@ -25,7 +27,7 @@ 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]
class TournamentMatchMaker:
def __init__(self):
@ -82,7 +84,7 @@ class TournamentMatchMaker:
while len(players) > 1:
self.current_round += 1
print(f"Starting round {self.current_round} with {len(players)} players")
self.create_matches(players)
await self.create_matches(players)
await self.update_brackets()
await self.start_round_matches()
# Wait for all matches in the current round to finish
@ -96,14 +98,24 @@ class TournamentMatchMaker:
await self.update_brackets()
await self.end_tournament(players[0] if players else None)
def create_matches(self, players):
async def create_matches(self, players):
matches = []
for i in range(0, len(players), 2):
self.games += 1
if i + 1 < len(players):
matches.append(TournamentMatch(self.games, players[i], players[i + 1], self))
# Create a new instance of TournamentMatch for this round
match = TournamentMatch(self.games, players[i], players[i + 1], self)
matches.append(match)
else:
matches.append(TournamentMatch(self.games, players[i], None, self)) # BYE match
# Create a BYE match where the second player is None
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 i + 1 < len(players):
await players[i + 1].set_game(match)
self.rounds.append(matches)
self.matches.extend(matches)

View File

@ -64,7 +64,6 @@ document.addEventListener('DOMContentLoaded', () => {
quickMatchButton.addEventListener('click', startQuickMatch);
tournamentButton.addEventListener('click', startTournament);
async function handleCheckNickname() {
const nickname = nicknameInput.value.trim();
if (nickname) {
@ -185,7 +184,6 @@ document.addEventListener('DOMContentLoaded', () => {
return data.authenticated;
}
async function handleCheckNickname2() {
const nickname2 = nicknameInput2.value.trim();
if (nickname2) {

View File

@ -110,8 +110,8 @@
</div>
<div id="game1" style="display: none;">
<div id="player1-name" class="name">Player 1</div>
<div id="player2-name" class="name">Player 2</div>
<div id="player1-name" class="name"></div>
<div id="player2-name" class="name"></div>
<div id="game2">
<div id="player1-score" class="score">0</div>
<div id="player2-score" class="score">0</div>