mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2026-11-09 17:37:08 +01:00
up
This commit is contained in:
@@ -9,6 +9,7 @@ from asgiref.sync import sync_to_async
|
||||
from .models import Tournoi
|
||||
|
||||
class Game:
|
||||
|
||||
def __init__(self, game_id, player1, player2, localgame):
|
||||
self.game_id = game_id
|
||||
self.player1 = player1
|
||||
@@ -43,12 +44,14 @@ class Game:
|
||||
}
|
||||
self.speed = 1
|
||||
self.game_loop_task = None
|
||||
self.database = None
|
||||
self.ended = False
|
||||
self.p1_mov = 0
|
||||
self.p2_mov = 0
|
||||
self.bt1 = 0
|
||||
self.bt2 = 0
|
||||
self.start_time = datetime.now()
|
||||
self.future_ball_position = {'x': 390, 'y': 190}
|
||||
|
||||
async def start_game(self):
|
||||
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']}) --- ({self})")
|
||||
@@ -57,41 +60,42 @@ class Game:
|
||||
|
||||
async def game_loop(self):
|
||||
print(" In the game loop..")
|
||||
x = 0
|
||||
x = 59
|
||||
while not self.ended:
|
||||
if self.botgame:
|
||||
x += 1
|
||||
if x == 60:
|
||||
await self.update_bot_position()
|
||||
# Random BOT difficulty..
|
||||
steps = 60#random.randint(10, 60)
|
||||
self.future_ball_position = await self.predict_ball_trajectory(steps)
|
||||
x = 0
|
||||
if self.botgame:
|
||||
await self.update_bot_position()
|
||||
await self.handle_pad_movement()
|
||||
await self.update_game_state()
|
||||
await self.send_game_state()
|
||||
await asyncio.sleep(1/60) # Around 60 FPS
|
||||
|
||||
async def update_bot_position(self):
|
||||
future_ball_position = self.predict_ball_trajectory()
|
||||
|
||||
target_y = future_ball_position['y']
|
||||
#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
|
||||
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)
|
||||
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)
|
||||
self.p2_mov = -1
|
||||
#self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0)
|
||||
|
||||
def predict_ball_trajectory(self, steps=60):
|
||||
|
||||
async def predict_ball_trajectory(self, steps=60):
|
||||
future_x = self.game_state['ball_position']['x']
|
||||
future_y = self.game_state['ball_position']['y']
|
||||
velocity_x = self.game_state['ball_velocity']['x']
|
||||
velocity_y = self.game_state['ball_velocity']['y']
|
||||
|
||||
for _ in range(steps):
|
||||
future_x += velocity_x
|
||||
if future_x <= 10:
|
||||
@@ -101,11 +105,9 @@ class Game:
|
||||
future_x = 790
|
||||
else:
|
||||
future_y += velocity_y
|
||||
|
||||
# Dealing with bounces off walls
|
||||
if future_y <= 10 or future_y >= 390:
|
||||
velocity_y = -velocity_y # Reverse the direction of vertical movement
|
||||
|
||||
# Dealing with bounces off walls
|
||||
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}
|
||||
|
||||
async def update_game_state(self):
|
||||
@@ -216,8 +218,8 @@ 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()
|
||||
#if self.game_loop_task:
|
||||
# self.game_loop_task.cancel()
|
||||
print(f"- Game #{self.game_id} ENDED --- ({self})")
|
||||
|
||||
end_time = datetime.now()
|
||||
@@ -233,7 +235,8 @@ class Game:
|
||||
})
|
||||
if not self.botgame:
|
||||
if not self.localgame:
|
||||
await remaining_player.send(message)
|
||||
await remaining_player.send(message)
|
||||
|
||||
# Notify both players that the game has ended
|
||||
end_message = json.dumps({
|
||||
'type': 'game_ended',
|
||||
@@ -243,11 +246,15 @@ class Game:
|
||||
if not self.botgame:
|
||||
if not self.localgame:
|
||||
await self.player2.send(end_message)
|
||||
if hasattr(self, 'tournament'):
|
||||
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, True, self.tournament.tournoi_reg)
|
||||
else:
|
||||
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, False, None)
|
||||
|
||||
avd, d = (True, self.tournament.tournoi_reg) if hasattr(self, 'tournament') else (False, None)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-31 16:01
|
||||
# Generated by Django 5.1.1 on 2024-09-13 11:41
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
@@ -20,12 +20,6 @@ class Migration(migrations.Migration):
|
||||
('total_match', models.PositiveSmallIntegerField(default=0)),
|
||||
('total_win', models.PositiveSmallIntegerField(default=0)),
|
||||
('p_win', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_adv_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('best_score', models.PositiveSmallIntegerField(default=0)),
|
||||
('m_nbr_ball_touch', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('total_duration', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)),
|
||||
('m_duration', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('num_participated_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
('num_won_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
],
|
||||
@@ -36,7 +30,7 @@ class Migration(migrations.Migration):
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=200)),
|
||||
('nbr_player', models.PositiveSmallIntegerField()),
|
||||
('date', models.DateField()),
|
||||
('date', models.DateField(auto_now_add=True)),
|
||||
('winner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='game.player')),
|
||||
],
|
||||
),
|
||||
@@ -53,7 +47,7 @@ class Migration(migrations.Migration):
|
||||
('is_tournoi', models.BooleanField()),
|
||||
('player1', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player1', to='game.player')),
|
||||
('player2', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player2', to='game.player')),
|
||||
('winner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player')),
|
||||
('winner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player')),
|
||||
('tournoi', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='matches', to='game.tournoi')),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 09:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player1',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player2',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
]
|
||||
@@ -1,19 +0,0 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-31 16:04
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player'),
|
||||
),
|
||||
]
|
||||
18
pong/game/migrations/0003_alter_tournoi_winner.py
Normal file
18
pong/game/migrations/0003_alter_tournoi_winner.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 11:56
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0002_alter_match_player1_alter_match_player2_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='winner',
|
||||
field=models.CharField(max_length=200),
|
||||
),
|
||||
]
|
||||
@@ -1,4 +1,4 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-10 14:17
|
||||
# Generated by Django 5.1.1 on 2024-09-14 12:03
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
@@ -6,13 +6,13 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0002_alter_match_winner'),
|
||||
('game', '0003_alter_tournoi_winner'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='date',
|
||||
field=models.DateField(auto_now_add=True),
|
||||
name='winner',
|
||||
field=models.CharField(blank=True, max_length=200, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 12:41
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0004_alter_tournoi_winner'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='player',
|
||||
name='num_won_tournaments',
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-15 14:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0005_remove_player_num_won_tournaments'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='best_score',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_duration',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_nbr_ball_touch',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_score_adv_match',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_score_match',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='num_won_tournaments',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='total_duration',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player1',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player1', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player2',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player2', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='game.player'),
|
||||
),
|
||||
]
|
||||
@@ -11,13 +11,6 @@ from .utils import create_tournament, update_tournament, getlen
|
||||
from asgiref.sync import sync_to_async
|
||||
from .views import write_data
|
||||
|
||||
|
||||
TOURNAMENT_NAMES = [
|
||||
"Champions Clash", "Ultimate Showdown", "Battle Royale",
|
||||
"Victory Cup", "Legends Tournament", "Elite Series", "Clash of 42",
|
||||
"Shibuya incident", "Cunning Game", "Elite of the Stars"
|
||||
]
|
||||
|
||||
TOURNAMENT_NAMES = [
|
||||
"Champion's Clash", "Ultimate Showdown", "Battle Royale",
|
||||
"Victory's Cup", "Legends Tournament", "Elite Series", "Clash of 42",
|
||||
@@ -90,13 +83,13 @@ class TournamentMatchMaker:
|
||||
|
||||
# Tournament start method
|
||||
async def start_tournament(self):
|
||||
|
||||
if len(self.waiting_players) < 2:
|
||||
if len(self.waiting_players) < 3:
|
||||
return False
|
||||
if len(self.waiting_players) % 2 == 0:
|
||||
await self.add_player(None)
|
||||
self.tournament_state = "in_progress"
|
||||
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)()
|
||||
self.final_name = self.name + " #" + str(len_tournament + 1)
|
||||
@@ -105,7 +98,7 @@ class TournamentMatchMaker:
|
||||
return True
|
||||
|
||||
async def advance_tournament(self):
|
||||
players = self.waiting_players
|
||||
players = self.waiting_players
|
||||
while len(players) > 1:
|
||||
self.current_round += 1
|
||||
print(f"Starting round {self.current_round} with {len(players)} players")
|
||||
@@ -188,6 +181,14 @@ class TournamentMatchMaker:
|
||||
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!")
|
||||
|
||||
async def send_game_text(self, player, text):
|
||||
message = json.dumps({
|
||||
'type': 'game_text_update',
|
||||
'game_text': text
|
||||
})
|
||||
await player.send(message)
|
||||
|
||||
def get_round_winners(self):
|
||||
winners = []
|
||||
@@ -219,6 +220,7 @@ class TournamentMatchMaker:
|
||||
self.rounds = []
|
||||
self.current_round = 0
|
||||
self.games = 0
|
||||
self.tournament_state = "waiting"
|
||||
|
||||
async def handle_match_end(self, match):
|
||||
await self.update_brackets()
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# /pong/game/utils.py
|
||||
|
||||
from .models import Player, Tournoi, Match
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
@@ -10,10 +12,14 @@ def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tour
|
||||
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")
|
||||
|
||||
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}")
|
||||
@@ -65,6 +71,7 @@ def create_player(
|
||||
m_duration=m_duration,
|
||||
num_participated_tournaments=num_participated_tournaments,
|
||||
num_won_tournaments=num_won_tournaments
|
||||
|
||||
)
|
||||
player.save()
|
||||
return player
|
||||
@@ -98,10 +105,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()
|
||||
|
||||
@@ -122,13 +133,13 @@ def update_player_statistics(player_name):
|
||||
return
|
||||
|
||||
won_matches = Match.objects.filter(winner=player)
|
||||
#part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player1=player)
|
||||
#part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player2=player)
|
||||
#won_tourn = Tournoi.objects.filter(winner=player)
|
||||
part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player1=player)
|
||||
part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player2=player)
|
||||
won_tourn = Tournoi.objects.filter(winner=player)
|
||||
|
||||
total_score = matches_as_player1.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
total_score += matches_as_player2.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
|
||||
|
||||
total_score_adv = matches_as_player1.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
total_score_adv += matches_as_player2.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
|
||||
@@ -146,9 +157,9 @@ def update_player_statistics(player_name):
|
||||
total_duration += matches_as_player2.aggregate(Sum('duration'))['duration__sum'] or 0
|
||||
m_duration = total_duration / total_match
|
||||
|
||||
#total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
#total_win_tourn = won_tourn.count()
|
||||
#p_win_tourn = (total_win_tourn / total_tourn_p) * 100 if total_tourn_p else 0
|
||||
total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
total_win_tourn = won_tourn.count()
|
||||
p_win_tourn = (total_win_tourn / total_tourn_p) * 100 if total_tourn_p else 0
|
||||
|
||||
best_score_as_player1 = matches_as_player1.aggregate(Max('score_player1'))['score_player1__max'] or 0
|
||||
best_score_as_player2 = matches_as_player2.aggregate(Max('score_player2'))['score_player2__max'] or 0
|
||||
@@ -163,8 +174,8 @@ def update_player_statistics(player_name):
|
||||
player.m_nbr_ball_touch = m_nbr_ball_touch
|
||||
player.total_duration = total_duration
|
||||
player.m_duration = m_duration
|
||||
# player.num_participated_tournaments = total_tourn_p
|
||||
#player.num_won_tournaments = total_win_tourn
|
||||
player.num_participated_tournaments = total_tourn_p
|
||||
player.num_won_tournaments = total_win_tourn
|
||||
|
||||
player.save()
|
||||
|
||||
@@ -193,4 +204,4 @@ def update_tournament(name_tournoi, winner_name):
|
||||
|
||||
|
||||
def getlen():
|
||||
return Tournoi.objects.count()
|
||||
return Tournoi.objects.count()
|
||||
@@ -91,15 +91,22 @@ def player_list_json(request):
|
||||
}
|
||||
return JsonResponse(data)
|
||||
|
||||
def tournoi_list_json(request):
|
||||
tournois = Tournoi.objects.all()
|
||||
|
||||
data = {
|
||||
'tournois': list(tournois.values(
|
||||
'id', 'name', 'nbr_player', 'date', 'winner'
|
||||
))
|
||||
def get_tournoi_data(tournoi):
|
||||
return {
|
||||
"id": tournoi.id,
|
||||
"name": tournoi.name,
|
||||
"nbr_player": tournoi.nbr_player,
|
||||
"date": tournoi.date,
|
||||
"winner": {
|
||||
"id": tournoi.winner.id,
|
||||
"name": tournoi.winner.name
|
||||
} if tournoi.winner else None
|
||||
}
|
||||
return JsonResponse(data)
|
||||
|
||||
def tournoi_list_json(request):
|
||||
tournois = Tournoi.objects.select_related('winner').all() # Charge les données du gagnant
|
||||
tournois_data = [get_tournoi_data(tournoi) for tournoi in tournois]
|
||||
return JsonResponse({"tournois": tournois_data})
|
||||
|
||||
|
||||
import os
|
||||
|
||||
@@ -13,7 +13,6 @@ from pathlib import Path
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
|
||||
|
||||
@@ -29,14 +28,15 @@ ALLOWED_HOSTS = ['*']
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
#'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
#'django.contrib.sessions',
|
||||
#'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'channels',
|
||||
'pong.game',
|
||||
#'django_db_conn_pool',
|
||||
'rest_framework'
|
||||
]
|
||||
|
||||
@@ -46,7 +46,7 @@ MIDDLEWARE = [
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
#'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
@@ -81,6 +81,7 @@ DATABASES = {
|
||||
'PASSWORD': os.getenv('DB_PASSWORD'),
|
||||
'HOST': os.getenv('DB_HOST'),
|
||||
'PORT': '5432',
|
||||
'CONN_MAX_AGE': None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,6 +137,32 @@ CHANNEL_LAYERS = {
|
||||
},
|
||||
}
|
||||
|
||||
LOGGING = {
|
||||
'version': 1, # Django requires this key
|
||||
'disable_existing_loggers': False, # Keep Django's default loggers
|
||||
'formatters': {
|
||||
'simple': {
|
||||
'format': '{levelname} {message}',
|
||||
'style': '{', # Allows to use Python's new style string formatting
|
||||
},
|
||||
},
|
||||
'handlers': {
|
||||
'console': { # Log to the console
|
||||
'level': 'DEBUG', # Minimum level of messages that should be handled
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'simple', # Use the simple formatter defined above
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'django': { # The main logger for Django itself
|
||||
'handlers': ['console'],
|
||||
'level': 'DEBUG', # Minimum log level to be logged
|
||||
'propagate': False, # Prevents log propagation to other loggers
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
"""
|
||||
LOGGING = {
|
||||
'version': 1, # The version of the logging configuration schema
|
||||
'disable_existing_loggers': False, # Allows existing loggers to keep logging
|
||||
@@ -170,3 +197,4 @@ LOGGING = {
|
||||
},
|
||||
},
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -103,10 +103,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying matches:');
|
||||
const matchListBody = document.querySelector('#match-list tbody');
|
||||
matchListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
|
||||
if (matches.length != 0) {
|
||||
matches.forEach(match => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${match.id}</td>
|
||||
<td>${match.player1__name}</td>
|
||||
@@ -124,6 +125,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
matchListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
`;
|
||||
@@ -135,10 +137,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying players:');
|
||||
const playersListBody = document.querySelector('#player-list tbody');
|
||||
playersListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
|
||||
if (players.length != 0) {
|
||||
players.forEach(player => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${player.id}</td>
|
||||
<td>${player.name}</td>
|
||||
@@ -157,8 +160,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
playersListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
<td colspan="12">No player found.</td>
|
||||
`
|
||||
playersListBody.appendChild(row);
|
||||
}
|
||||
@@ -168,22 +172,25 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying tournois:');
|
||||
const tournoisListBody = document.querySelector('#tournoi-list tbody');
|
||||
tournoisListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
if (tournois.length != 0) {
|
||||
tournois.forEach(tournoi => {
|
||||
console.log('Winner:', tournoi.winner); //debug !!!!!!!!!!!!!!!!!
|
||||
console.log('Winner:', tournoi.winner__name); //debug !!!!!!!!!!!!!!!!!
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${tournoi.id}</td>
|
||||
<td>${tournoi.name}</td>
|
||||
<td>${tournoi.nbr_player}</td>
|
||||
<td>${tournoi.date}</td>
|
||||
<td>${tournoi.winner ? tournoi.winner.name : 'None'}</td>
|
||||
<td>${tournoi.winner ? tournoi.winner.name : 'No one yet ...'}</td>
|
||||
`;
|
||||
tournoisListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
<td colspan="12">No tournoi found.</td>
|
||||
`
|
||||
tournoisListBody.appendChild(row);
|
||||
}
|
||||
|
||||
BIN
pong/static/favicon.ico
Normal file
BIN
pong/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -360,7 +360,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
function startWebSocketConnection(token, players) {
|
||||
socket = new WebSocket(`ws://${window.location.host}/ws/game/`);
|
||||
socket = new WebSocket(`wss://${window.location.host}/ws/game/`);
|
||||
|
||||
socket.onopen = function (event) {
|
||||
console.log('WebSocket connection established');
|
||||
@@ -388,6 +388,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
} else if (data.type === 'game_state_update') {
|
||||
updateGameState(data.game_state);
|
||||
} else if (data.type === 'game_text_update') {
|
||||
updateGameText(data.game_text);
|
||||
} else if (data.type === 'player_disconnected') {
|
||||
console.log('Player disconnected:', data.player);
|
||||
} else if (data.type === 'game_ended') {
|
||||
@@ -462,6 +464,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.getElementById('game-text').textContent = gameState.game_text;
|
||||
}
|
||||
|
||||
function updateGameText(gameText) {
|
||||
document.getElementById('game-text').textContent = gameText;
|
||||
}
|
||||
|
||||
const starsContainer = document.getElementById('stars');
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const star = document.createElement('div');
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pong Game</title>
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}?v=3">
|
||||
<div class="logo">
|
||||
<img src="{% static 'logo-42-perpignan.png' %}" alt="Logo">
|
||||
</div>
|
||||
<link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}?v=2" >
|
||||
<div class="logo">
|
||||
<img src="{% static 'logo-42-perpignan.png' %}" alt="Logo">
|
||||
</div>
|
||||
</head>
|
||||
<body>
|
||||
<div class="language-switcher">
|
||||
|
||||
Reference in New Issue
Block a user