mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2025-12-16 14:07:49 +01:00
tournament WORKING and bot AI fixed somehow
This commit is contained in:
parent
878cf92bbb
commit
3e0c3aa3bb
@ -6,6 +6,7 @@ from django.contrib.auth.models import User
|
|||||||
from channels.db import database_sync_to_async
|
from channels.db import database_sync_to_async
|
||||||
from .matchmaking import match_maker
|
from .matchmaking import match_maker
|
||||||
from .tournament import tournament_match_maker
|
from .tournament import tournament_match_maker
|
||||||
|
import asyncio
|
||||||
|
|
||||||
class GameConsumer(AsyncWebsocketConsumer):
|
class GameConsumer(AsyncWebsocketConsumer):
|
||||||
async def connect(self):
|
async def connect(self):
|
||||||
@ -24,11 +25,10 @@ class GameConsumer(AsyncWebsocketConsumer):
|
|||||||
elif data['type'] == 'key_press':
|
elif data['type'] == 'key_press':
|
||||||
if self.game:
|
if self.game:
|
||||||
await self.game.handle_key_press(self, data['key'])
|
await self.game.handle_key_press(self, data['key'])
|
||||||
else:
|
|
||||||
await match_maker.handle_key_press(self, data['key'])
|
|
||||||
elif data['type'] == 'start_tournament':
|
elif data['type'] == 'start_tournament':
|
||||||
print("Start TOURNAMENT received..")
|
print(f"Start TOURNAMENT received by {self.user}")
|
||||||
await tournament_match_maker.start_tournament()
|
# Run the tournament in the background
|
||||||
|
asyncio.create_task(tournament_match_maker.start_tournament())
|
||||||
|
|
||||||
async def authenticate(self, token):
|
async def authenticate(self, token):
|
||||||
user = await self.get_user_from_token(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")
|
print(f"User {self.user.username if hasattr(self, 'user') else 'Unknown'} disconnected")
|
||||||
|
|
||||||
async def set_game(self, game):
|
async def set_game(self, game):
|
||||||
|
print(f"({self.user}) Game set to: {game}")
|
||||||
self.game = game
|
self.game = game
|
||||||
|
|||||||
@ -49,7 +49,7 @@ class Game:
|
|||||||
self.start_time = datetime.now()
|
self.start_time = datetime.now()
|
||||||
|
|
||||||
async def start_game(self):
|
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())
|
self.game_loop_task = asyncio.create_task(self.game_loop())
|
||||||
print(f" Begin MATCH at: {self.start_time}")
|
print(f" Begin MATCH at: {self.start_time}")
|
||||||
|
|
||||||
@ -77,8 +77,10 @@ class Game:
|
|||||||
if player2_position < target_y < player2_position + 80:
|
if player2_position < target_y < player2_position + 80:
|
||||||
pass #bot already placed
|
pass #bot already placed
|
||||||
elif player2_position < target_y:
|
elif player2_position < target_y:
|
||||||
|
#self.p2_mov = 1
|
||||||
self.game_state['player2_position'] = min(player2_position + (50 * self.speed), 300)
|
self.game_state['player2_position'] = min(player2_position + (50 * self.speed), 300)
|
||||||
elif player2_position + 80 > target_y:
|
elif player2_position + 80 > target_y:
|
||||||
|
#self.p2_mov = -1
|
||||||
self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0)
|
self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0)
|
||||||
|
|
||||||
def predict_ball_trajectory(self, steps=60):
|
def predict_ball_trajectory(self, steps=60):
|
||||||
@ -90,10 +92,16 @@ class Game:
|
|||||||
|
|
||||||
for _ in range(steps):
|
for _ in range(steps):
|
||||||
future_x += velocity_x
|
future_x += velocity_x
|
||||||
future_y += velocity_y
|
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
|
# 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
|
velocity_y = -velocity_y # Reverse the direction of vertical movement
|
||||||
|
|
||||||
return {'x': future_x, 'y': future_y}
|
return {'x': future_x, 'y': future_y}
|
||||||
@ -208,7 +216,7 @@ class Game:
|
|||||||
self.ended = True
|
self.ended = True
|
||||||
if self.game_loop_task:
|
if self.game_loop_task:
|
||||||
self.game_loop_task.cancel()
|
self.game_loop_task.cancel()
|
||||||
print(f"- Game #{self.game_id} ENDED")
|
print(f"- Game #{self.game_id} ENDED --- ({self})")
|
||||||
|
|
||||||
end_time = datetime.now()
|
end_time = datetime.now()
|
||||||
duration = (end_time - self.start_time).total_seconds() / 60
|
duration = (end_time - self.start_time).total_seconds() / 60
|
||||||
|
|||||||
@ -26,7 +26,8 @@ class MatchMaker:
|
|||||||
for game in self.active_games.values():
|
for game in self.active_games.values():
|
||||||
if player in [game.player1, game.player2]:
|
if player in [game.player1, game.player2]:
|
||||||
await game.end_game(disconnected_player=player)
|
await game.end_game(disconnected_player=player)
|
||||||
del self.active_games[game.game_id]
|
if game.game_id in self.active_games:
|
||||||
|
del self.active_games[game.game_id]
|
||||||
break
|
break
|
||||||
|
|
||||||
async def match_loop(self):
|
async def match_loop(self):
|
||||||
@ -102,11 +103,5 @@ class MatchMaker:
|
|||||||
'player2': 'BOT'
|
'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
|
# Instance of the class
|
||||||
match_maker = MatchMaker()
|
match_maker = MatchMaker()
|
||||||
|
|||||||
@ -14,9 +14,11 @@ class TournamentMatch(Game):
|
|||||||
# Store the current game instance in active games
|
# Store the current game instance in active games
|
||||||
match_maker.active_games[game_id] = self
|
match_maker.active_games[game_id] = self
|
||||||
# Set the game for the players
|
# 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:
|
if player2:
|
||||||
player2.set_game(self)
|
player2.set_game(self)
|
||||||
|
print(f"{player2.user.username} set to game #{self}")'''
|
||||||
# Store the tournament instance
|
# Store the tournament instance
|
||||||
self.tournament = tournament
|
self.tournament = tournament
|
||||||
|
|
||||||
@ -25,7 +27,7 @@ class TournamentMatch(Game):
|
|||||||
await super().end_game(disconnected_player)
|
await super().end_game(disconnected_player)
|
||||||
# Handle the end of the match in the tournament context
|
# Handle the end of the match in the tournament context
|
||||||
await self.tournament.handle_match_end(self)
|
await self.tournament.handle_match_end(self)
|
||||||
|
del match_maker.active_games[self.game_id]
|
||||||
|
|
||||||
class TournamentMatchMaker:
|
class TournamentMatchMaker:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
@ -82,7 +84,7 @@ class TournamentMatchMaker:
|
|||||||
while len(players) > 1:
|
while len(players) > 1:
|
||||||
self.current_round += 1
|
self.current_round += 1
|
||||||
print(f"Starting round {self.current_round} with {len(players)} players")
|
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.update_brackets()
|
||||||
await self.start_round_matches()
|
await self.start_round_matches()
|
||||||
# Wait for all matches in the current round to finish
|
# Wait for all matches in the current round to finish
|
||||||
@ -96,14 +98,24 @@ class TournamentMatchMaker:
|
|||||||
await self.update_brackets()
|
await self.update_brackets()
|
||||||
await self.end_tournament(players[0] if players else None)
|
await self.end_tournament(players[0] if players else None)
|
||||||
|
|
||||||
def create_matches(self, players):
|
async def create_matches(self, players):
|
||||||
matches = []
|
matches = []
|
||||||
for i in range(0, len(players), 2):
|
for i in range(0, len(players), 2):
|
||||||
self.games += 1
|
self.games += 1
|
||||||
if i + 1 < len(players):
|
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:
|
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.rounds.append(matches)
|
||||||
self.matches.extend(matches)
|
self.matches.extend(matches)
|
||||||
|
|
||||||
|
|||||||
@ -64,7 +64,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
quickMatchButton.addEventListener('click', startQuickMatch);
|
quickMatchButton.addEventListener('click', startQuickMatch);
|
||||||
tournamentButton.addEventListener('click', startTournament);
|
tournamentButton.addEventListener('click', startTournament);
|
||||||
|
|
||||||
|
|
||||||
async function handleCheckNickname() {
|
async function handleCheckNickname() {
|
||||||
const nickname = nicknameInput.value.trim();
|
const nickname = nicknameInput.value.trim();
|
||||||
if (nickname) {
|
if (nickname) {
|
||||||
@ -185,7 +184,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
return data.authenticated;
|
return data.authenticated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function handleCheckNickname2() {
|
async function handleCheckNickname2() {
|
||||||
const nickname2 = nicknameInput2.value.trim();
|
const nickname2 = nicknameInput2.value.trim();
|
||||||
if (nickname2) {
|
if (nickname2) {
|
||||||
|
|||||||
@ -110,8 +110,8 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="game1" style="display: none;">
|
<div id="game1" style="display: none;">
|
||||||
<div id="player1-name" class="name">Player 1</div>
|
<div id="player1-name" class="name"></div>
|
||||||
<div id="player2-name" class="name">Player 2</div>
|
<div id="player2-name" class="name"></div>
|
||||||
<div id="game2">
|
<div id="game2">
|
||||||
<div id="player1-score" class="score">0</div>
|
<div id="player1-score" class="score">0</div>
|
||||||
<div id="player2-score" class="score">0</div>
|
<div id="player2-score" class="score">0</div>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user