Merge pull request #1 from AudebertAdrien/adrien

Adrien
This commit is contained in:
Adrien Audebert 2024-09-11 14:48:55 +02:00 committed by GitHub
commit d2cb453638
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
36 changed files with 2964 additions and 802 deletions

20
.env
View File

@ -8,8 +8,24 @@ POSTGRES_DB=players_db
POSTGRES_USER=42student
POSTGRES_PASSWORD=qwerty
# Django settings
DB_HOST=db
DB_PORT=5432
PWD_PATH=${PWD}
PROJECT_PATH=${PWD_PATH}/pong
# ElasticSearch settings
STACK_VERSION=8.14.3
CLUSTER_NAME=docker-cluster
LICENSE=basic
ELASTIC_USERNAME=elastic
ELASTIC_PASSWORD=elastic_pass
# Kibana settings
KIBANA_PORT=5601
KIBANA_USERNAME=kibana_system
KIBANA_PASSWORD=kibana_pass
ENCRYPTION_KEY=c34d38b3a14956121ff2170e5030b471551370178f43e5626eec58b04a30fae2
PROJECT_PATH=/home/mchiboub/42cursus/transcendence/pong
POSTGRES_DATA_PATH=/home/mchiboub/42cursus/transcendence/data/db

2
.gitignore vendored
View File

@ -1,5 +1,3 @@
venv/
__pycache__/
data/
.env
makefile

View File

@ -15,4 +15,4 @@ RUN python3 -m venv venv
RUN venv/bin/pip3 install --upgrade pip
RUN venv/bin/pip3 install --no-cache-dir -r requirements.txt
EXPOSE 80
EXPOSE 8080

28
config/logstash.conf Normal file
View File

@ -0,0 +1,28 @@
input {
file {
path => "/usr/share/logstash/logs/django.log"
start_position => "beginning"
sincedb_path => "/dev/null"
codec => "json"
}
}
filter {
json {
source => "message"
target => "json_message"
}
}
output {
elasticsearch {
hosts => ["https://es01:9200"]
user => "elastic"
password => "${ELASTIC_PASSWORD}"
ssl_enabled => true
ssl_certificate_authorities => "/usr/share/logstash/certs/ca/ca.crt"
ssl_verification_mode => "full"
index => "django-logs-%{+YYYY.MM.dd}"
}
stdout { codec => rubydebug }
}

View File

@ -1,70 +0,0 @@
services:
db:
image: postgres:latest
container_name: postgres
restart: always
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
networks:
- app-network
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
backend:
build:
context: .
dockerfile: Dockerfile
image: backend
container_name: backend
restart: always
command: /bin/sh -c "sleep 5 &&
venv/bin/python manage.py makemigrations --noinput &&
venv/bin/python manage.py migrate --noinput &&
venv/bin/python manage.py collectstatic --noinput &&
venv/bin/daphne -b 0.0.0.0 -p 80 pong.asgi:application"
volumes:
- pong:/transcendence/pong
ports:
- "80:80"
depends_on:
- db
networks:
- app-network
environment:
DB_HOST: db
DB_PORT: 5432
DB_NAME: ${POSTGRES_DB}
DB_USER: ${POSTGRES_USER}
DB_PASSWORD: ${POSTGRES_PASSWORD}
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:80 || exit 1"]
interval: 10s
timeout: 5s
retries: 5
volumes:
postgres_data:
driver: local
driver_opts:
type: none
device: ${POSTGRES_DATA_PATH}
o: bind
pong:
driver: local
driver_opts:
type: none
device: ${PROJECT_PATH}
o: bind
networks:
app-network:
driver: bridge

236
docker-compose.yml Normal file
View File

@ -0,0 +1,236 @@
services:
setup:
image: docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION}
container_name: setup
user: "0"
volumes:
- certs:/usr/share/elasticsearch/config/certs
command: >
bash -c '
if [ x${ELASTIC_PASSWORD} == x ]; then
echo "Set the ELASTIC_PASSWORD environment variable in the .env file";
exit 1;
elif [ x${KIBANA_PASSWORD} == x ]; then
echo "Set the KIBANA_PASSWORD environment variable in the .env file";
exit 1;
fi;
if [ ! -f config/certs/ca.zip ]; then
echo "Creating CA";
bin/elasticsearch-certutil ca --silent --pem -out config/certs/ca.zip;
unzip config/certs/ca.zip -d config/certs;
fi;
if [ ! -f config/certs/certs.zip ]; then
echo "Creating certs";
echo -ne \
"instances:\n"\
" - name: es01\n"\
" dns:\n"\
" - es01\n"\
" - localhost\n"\
" ip:\n"\
" - 127.0.0.1\n"\
" - name: kibana\n"\
" dns:\n"\
" - kibana\n"\
" - localhost\n"\
" ip:\n"\
" - 127.0.0.1\n"\
> config/certs/instances.yml;
bin/elasticsearch-certutil cert --silent --pem -out config/certs/certs.zip --in config/certs/instances.yml --ca-cert config/certs/ca/ca.crt --ca-key config/certs/ca/ca.key;
unzip config/certs/certs.zip -d config/certs;
fi;
echo "Setting file permissions"
chown -R root:root config/certs;
find . -type d -exec chmod 750 \{\} \;;
find . -type f -exec chmod 640 \{\} \;;
echo "Waiting for Elasticsearch availability";
until curl -s --cacert config/certs/ca/ca.crt https://es01:9200 | grep -q "missing authentication credentials"; do sleep 30; done;
echo "Setting kibana_system password";
until curl -s -X POST --cacert config/certs/ca/ca.crt -u "elastic:${ELASTIC_PASSWORD}" -H "Content-Type: application/json" https://es01:9200/_security/user/kibana_system/_password -d "{\"password\":\"${KIBANA_PASSWORD}\"}" | grep -q "^{}"; do sleep 10; done;
echo "All done!";
'
healthcheck:
test: ["CMD-SHELL", "[ -f config/certs/es01/es01.crt ]"]
interval: 1s
timeout: 5s
retries: 120
backend:
build:
context: .
dockerfile: Dockerfile
image: backend
container_name: backend
restart: always
command: /bin/sh -c "sleep 5 &&
venv/bin/python manage.py makemigrations --noinput &&
venv/bin/python manage.py migrate --noinput &&
venv/bin/python manage.py collectstatic --noinput &&
venv/bin/daphne -b 0.0.0.0 -p 8080 pong.asgi:application"
volumes:
- pong:/transcendence/pong
- pong_django_logs:/transcendence/logs
ports:
- 8080:8080
networks:
- app-network
environment:
DB_HOST: db
DB_PORT: 5432
DB_NAME: ${POSTGRES_DB}
DB_USER: ${POSTGRES_USER}
DB_PASSWORD: ${POSTGRES_PASSWORD}
depends_on:
- db
healthcheck:
test: ["CMD-SHELL", "curl", "http://localhost:8080"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
db:
image: postgres:latest
container_name: postgres
restart: always
volumes:
- pong_pg_data:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- app-network
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
interval: 10s
timeout: 5s
retries: 5
es01:
image: docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION}
container_name: es01
depends_on:
setup:
condition: service_healthy
volumes:
- certs:/usr/share/elasticsearch/config/certs:ro
- pong_es_data_01:/usr/share/elasticsearch/data
labels:
co.elastic.logs/module: elasticsearch
ports:
- 9200:9200
environment:
- node.name=es01
- cluster.name=${CLUSTER_NAME}
- discovery.type=single-node
- ELASTIC_PASSWORD=${ELASTIC_PASSWORD}
- bootstrap.memory_lock=true
- xpack.security.enabled=true
- xpack.security.http.ssl.enabled=true
- xpack.security.http.ssl.key=certs/es01/es01.key
- xpack.security.http.ssl.certificate=certs/es01/es01.crt
- xpack.security.http.ssl.certificate_authorities=certs/ca/ca.crt
- xpack.security.transport.ssl.enabled=true
- xpack.security.transport.ssl.key=certs/es01/es01.key
- xpack.security.transport.ssl.certificate=certs/es01/es01.crt
- xpack.security.transport.ssl.certificate_authorities=certs/ca/ca.crt
- xpack.security.transport.ssl.verification_mode=certificate
- xpack.license.self_generated.type=${LICENSE}
healthcheck:
test:
[
"CMD-SHELL",
"curl -s --cacert config/certs/ca/ca.crt https://localhost:9200 | grep -q 'missing authentication credentials'",
]
interval: 10s
timeout: 10s
retries: 120
kibana:
image: docker.elastic.co/kibana/kibana:${STACK_VERSION}
container_name: kibana
labels:
co.elastic.logs/module: kibana
depends_on:
es01:
condition: service_healthy
volumes:
- certs:/usr/share/kibana/config/certs:ro
- pong_kibana:/usr/share/kibana/data
ports:
- 5601:5601
environment:
- SERVERNAME=kibana
- ELASTICSEARCH_HOSTS=https://es01:9200
- ELASTICSEARCH_USERNAME=${KIBANA_USERNAME}
- ELASTICSEARCH_PASSWORD=${KIBANA_PASSWORD}
- ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES=config/certs/ca/ca.crt
- XPACK_SECURITY_ENCRYPTIONKEY=${ENCRYPTION_KEY}
- XPACK_ENCRYPTEDSAVEDOBJECTS_ENCRYPTIONKEY=${ENCRYPTION_KEY}
- XPACK_REPORTING_ENCRYPTIONKEY=${ENCRYPTION_KEY}
healthcheck:
test:
[
"CMD-SHELL",
"curl -s -I http://localhost:5601 | grep -q 'HTTP/1.1 302 Found'"
]
interval: 10s
timeout: 10s
retries: 120
logstash01:
image: docker.elastic.co/logstash/logstash:${STACK_VERSION}
container_name: logstash01
labels:
co.elastic.logs/module: logstash
user: root
depends_on:
es01:
condition: service_healthy
kibana:
condition: service_healthy
volumes:
- certs:/usr/share/logstash/certs
- pong_logstash_data01:/usr/share/logstash/data
- ./config/logstash.conf:/usr/share/logstash/pipeline/logstash.conf:ro
- pong_django_logs:/usr/share/logstash/logs
ports:
- "5044:5044/udp"
command: logstash -f /usr/share/logstash/pipeline/logstash.conf
environment:
- NODE_NAME="logstash"
- ELASTIC_HOSTS=https://es01:9200
- ELASTIC_USER=${ELASTIC_USERNAME}
- ELASTIC_PASSWORD=${ELASTIC_PASSWORD}
- xpack.monitoring.enabled=false
volumes:
pong:
driver: local
driver_opts:
type: none
device: ${PROJECT_PATH}
o: bind
pong_django_logs:
driver: local
pong_pg_data:
driver: local
pong_es_data_01:
driver: local
pong_kibana:
driver: local
pong_logstash_data01:
driver: local
certs:
driver: local
networks:
app-network:
name: app-network
driver: bridge

View File

@ -1,15 +1,30 @@
# Django settings
SECRET_KEY=
SECRET_KEY="FollowTheWhiteRabbit"
DEBUG=True
DJANGO_ALLOWED_HOSTS=['*']
# PostgreSQL settings
POSTGRES_DB=players_db
POSTGRES_USER=42student
POSTGRES_PASSWORD=test
POSTGRES_PASSWORD=
# Django settings
DB_HOST=db
DB_PORT=5432
PWD_PATH=${PWD}
PROJECT_PATH=${PWD_PATH}/pong
PROJECT_PATH=${PWD}/pong
POSTGRES_DATA_PATH=${PWD}/data/db
# ElasticSearch settings
STACK_VERSION=8.14.3
CLUSTER_NAME=docker-cluster
LICENSE=basic
ELASTIC_USERNAME=elastic
ELASTIC_PASSWORD=
# Kibana settings
KIBANA_PORT=5601
KIBANA_USERNAME=kibana_system
KIBANA_PASSWORD=
ENCRYPTION_KEY=c34d38b3a14956121ff2170e5030b471551370178f43e5626eec58b04a30fae2

View File

@ -1,11 +1,10 @@
COMPOSE_FILE=docker-compose.yaml
COMPOSE_FILE=docker-compose.yml
COMPOSE=docker compose -f $(COMPOSE_FILE)
CONTAINER=$(c)
up: down
sudo mkdir -p data/db
$(COMPOSE) build
$(COMPOSE) up $(CONTAINER)
$(COMPOSE) up -d $(CONTAINER) || true
build:
$(COMPOSE) build $(CONTAINER)
@ -21,9 +20,13 @@ down:
destroy:
$(COMPOSE) down -v --rmi all
sudo rm -rf data
#sudo lsof -i :5432 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
#sudo lsof -i :80 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
kill-pid:
sudo lsof -i :5432 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
sudo lsof -i :5601 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
sudo lsof -i :9200 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
sudo lsof -i :8080 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
sudo lsof -i :5044 | awk 'NR>1 {print $$2}' | xargs sudo kill -9 || true
logs:
$(COMPOSE) logs -f $(CONTAINER)
@ -34,6 +37,8 @@ ps:
db-shell:
$(COMPOSE) exec db psql -U 42student players_db
re: destroy up
help:
@echo "Usage:"
@echo " make build [c=service] # Build images"
@ -42,7 +47,9 @@ help:
@echo " make down [c=service] # Stop and remove containers"
@echo " make destroy # Stop and remove containers and volumes"
@echo " make stop [c=service] # Stop containers"
@echo " make restart [c=service] # Restart containers"
@echo " make logs [c=service] # Tail logs of containers"
@echo " make ps # List containers"
@echo " make help # Show this help"
.PHONY: up build start stop down destroy logs ps db-shell help

1
manage.py Executable file → Normal file
View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

View File

@ -18,7 +18,7 @@ django.setup()
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import pong.game.routing # Import your routing module
import pong.game.routing
application = ProtocolTypeRouter({
"http": get_asgi_application(),

View File

@ -5,6 +5,8 @@ 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
import asyncio
class GameConsumer(AsyncWebsocketConsumer):
async def connect(self):
@ -16,11 +18,17 @@ class GameConsumer(AsyncWebsocketConsumer):
data = json.loads(text_data)
if data['type'] == 'authenticate':
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'])
else:
await match_maker.handle_key_press(self, data['key'])
elif data['type'] == '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)
@ -45,11 +53,54 @@ class GameConsumer(AsyncWebsocketConsumer):
await self.send(text_data=json.dumps({'type': 'waiting_room'}))
await match_maker.add_player(self)
async def authenticate2(self, token, token2):
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")
user2 = await self.get_user_from_token2(token2)
if user2:
self.user2 = user2
await self.send(text_data=json.dumps({'type': 'authenticated'}))
print(f"User {self.user2} authenticated")
await match_maker.create_game(self, None, True)
else:
await self.send(text_data=json.dumps({'type': 'error', 'message': 'Authentication failed'}))
print("Authentication failed")
else:
await self.send(text_data=json.dumps({'type': 'error', 'message': 'Authentication failed'}))
print("Authentication failed")
@database_sync_to_async
def get_user_from_token2(self, token):
try:
user2 = User.objects.filter(auth_token=token).first()
return user2
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.username} authenticated for tournament")
await self.join_tournament_waiting_room()
else:
await self.send(text_data=json.dumps({'type': 'error', 'message': 'Authentication failed'}))
print("Tournament 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):
print(f"({self.user}) Game set to: {game}")
self.game = game

View File

@ -3,69 +3,44 @@
import json
import asyncio
import random
from .utils import endfortheouche
class BotPlayer:
def __init__(self, game_state, speed):
self.game_state = game_state
self.speed = speed
async def update_bot_position(self):
print("Update bot position started")
try:
target_y = self.predict_ball_position()
#print(f"Target Y: {target_y}")
player2_position = self.game_state['player2_position']
#print(f"Player2 Position: {player2_position}")
if player2_position < target_y < player2_position + 80:
print("Bot is already aligned with the ball, no move needed.")
elif player2_position < target_y:
new_position = min(player2_position + (5 * self.speed), 300)
print(f"Moving bot down to {new_position}")
self.game_state['player2_position'] = new_position
elif player2_position + 80 > target_y:
new_position = max(player2_position - (5 * self.speed), 0)
print(f"Moving bot up to {new_position}")
self.game_state['player2_position'] = new_position
#await asyncio.sleep(1) # Rafraîchir toutes les secondes
except Exception as e:
print(f"Error in BotPlayer.update_bot_position: {e}")
def predict_ball_position(self):
# Prédire la future position de la balle en tenant compte de sa vitesse
ball_y = self.game_state['ball_position']['y']
ball_speed_y = self.game_state['ball_velocity']['y']
# Prédiction simple, peut être améliorée pour plus de précision
future_ball_y = ball_y + ball_speed_y * 1 # prédire pour la prochaine seconde
# Gérer les rebonds sur les limites
if future_ball_y < 0:
future_ball_y = -future_ball_y
elif future_ball_y > 300:
future_ball_y = 600 - future_ball_y
return future_ball_y
from datetime import datetime
from .utils import handle_game_data, getlen
from asgiref.sync import sync_to_async
from .models import Tournoi
class Game:
def __init__(self, game_id, player1, player2):
def __init__(self, game_id, player1, player2, localgame):
self.game_id = game_id
self.player1 = player1
self.player2 = player2
self.botgame = player2 is None
self.game_state = {
'player1_name': player1.user.username,
'player2_name': player2.user.username if player2 else 'BOT',
'player1_position': 150,
'player2_position': 150,
'ball_position': {'x': 390, 'y': 190},
'ball_velocity': {'x': random.choice([-5, 5]), 'y': random.choice([-5, 5])},
'player1_score': 0,
'player2_score': 0
}
self.localgame = localgame
if self.localgame:
self.botgame = False
self.game_state = {
'player1_name': player1.user.username,
'player2_name': player1.user2.username,
'player1_position': 150,
'player2_position': 150,
'ball_position': {'x': 390, 'y': 190},
'ball_velocity': {'x': random.choice([-5, 5]), 'y': random.choice([-5, 5])},
'player1_score': 0,
'player2_score': 0,
'game_text': ''
}
else:
# Set botgame to True if either player1 or player2 is None
self.botgame = player1 is None or player2 is None
self.game_state = {
'player1_name': player1.user.username if player1 else 'BOT',
'player2_name': player2.user.username if player2 else 'BOT',
'player1_position': 150,
'player2_position': 150,
'ball_position': {'x': 390, 'y': 190},
'ball_velocity': {'x': random.choice([-5, 5]), 'y': random.choice([-5, 5])},
'player1_score': 0,
'player2_score': 0,
'game-text': ''
}
self.speed = 1
self.game_loop_task = None
self.ended = False
@ -73,37 +48,69 @@ class Game:
self.p2_mov = 0
self.bt1 = 0
self.bt2 = 0
if self.botgame:
self.bot_player = BotPlayer(self.game_state, self.speed)
self.start_time = datetime.now()
async def start_game(self):
print(f"- Game #{self.game_id} STARTED")
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}")
async def game_loop(self):
#print("Here, ok")
while True:
print(" In the game loop..")
x = 0
while not self.ended:
if self.botgame:
#print('still ok')
#await self.bot_player.update_bot_position()
await self.update_bot_position()
#print('is it ok ?? ')
x += 1
if x == 60:
await self.update_bot_position()
x = 0
await self.handle_pad_movement()
self.update_game_state()
await self.update_game_state()
await self.send_game_state()
await asyncio.sleep(1/60) # Around 60 FPS
async def update_bot_position(self):
target_y = self.game_state['ball_position']['y']
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)
elif self.game_state['player2_position'] + 80 > target_y:
self.game_state['player2_position'] = max(self.game_state['player2_position'] - (5 * self.speed), 0)
future_ball_position = self.predict_ball_trajectory()
def update_game_state(self):
target_y = 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)
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):
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:
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 <= 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):
if self.ended:
return
# Update ball position
self.game_state['ball_position']['x'] += self.game_state['ball_velocity']['x']
self.game_state['ball_position']['y'] += self.game_state['ball_velocity']['y']
@ -123,16 +130,20 @@ class Game:
self.game_state['ball_velocity']['x'] *= -1
self.bt2 += 1
self.update_ball_velocity()
# Check for scoring
# 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'] >= 5:
self.end_game()
if self.game_state['player2_score'] > 2:
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'] >= 5:
self.end_game()
if self.game_state['player1_score'] > 2:
self.game_state['game_text'] = f"{self.game_state['player1_name']} WINS!"
await self.send_game_state()
await self.end_game()
self.reset_ball()
def reset_ball(self):
@ -164,30 +175,35 @@ class Game:
})
await self.player1.send(message)
if not self.botgame:
await self.player2.send(message)
if not self.localgame:
await self.player2.send(message)
async def handle_key_press(self, player, key):
if self.ended:
return
if player == self.player1:
print(f"Key press: {key}")
if key == 'arrowup':
self.p1_mov = -1
#self.game_state['player1_position'] = max(self.game_state['player1_position'] - 25, 0)
elif key == 'arrowdown':
self.p1_mov = 1
#self.game_state['player1_position'] = min(self.game_state['player1_position'] + 25, 300)
elif not self.botgame and player == self.player2:
if self.localgame:
if key == 'arrowup':
self.p2_mov = -1
elif key == 'arrowdown':
self.p2_mov = 1
elif key == 'w':
self.p1_mov = -1
elif key == 's':
self.p1_mov = 1
elif player == self.player1:
if key == 'arrowup':
self.p1_mov = -1
elif key == 'arrowdown':
self.p1_mov = 1
elif player == self.player2:
if key == 'arrowup':
self.p2_mov = -1
#self.game_state['player2_position'] = max(self.game_state['player2_position'] - 25, 0)
elif key == 'arrowdown':
self.p2_mov = 1
#self.game_state['player2_position'] = min(self.game_state['player2_position'] + 25, 300)
async def handle_pad_movement(self):
#print(f"P1 mov: {self.p1_mov}")
#print(f"P2 mov: {self.p2_mov}")
if self.ended:
return
if self.p1_mov == -1:
self.game_state['player1_position'] = max(self.game_state['player1_position'] - (5 * self.speed), 0)
elif self.p1_mov == 1:
@ -202,7 +218,11 @@ 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
# Notify that one player left the game
if disconnected_player:
remaining_player = self.player2 if disconnected_player == self.player1 else self.player1
@ -212,7 +232,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',
@ -220,23 +241,13 @@ class Game:
})
await self.player1.send(end_message)
if not self.botgame:
await self.player2.send(end_message)
await endfortheouche(self.game_state['player1_name'], self.game_state['player2_name'],
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, 42, False, None)
### pour Theo ###
# nickname player1
# nickname player2
# score p1
# score p2
# winner
# ball touch p1
# ball touch p2
# match time
# match type: 'quick match'
# match type: 'tournament'
# -> tournament id
#endfortheouche(p1, p2, s_p1, s_p2, bt_p1, bt_p2, dur, is_tournoi, name_tournament)
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)

View File

@ -26,7 +26,8 @@ class MatchMaker:
for game in self.active_games.values():
if player in [game.player1, game.player2]:
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
async def match_loop(self):
@ -35,12 +36,12 @@ class MatchMaker:
player1 = self.waiting_players.pop(0)
player2 = self.waiting_players.pop(0)
print(f"*** MATCH FOUND: {player1.user.username} vs {player2.user.username}")
await self.create_game(player1, player2)
await self.create_game(player1, player2, False)
else:
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
@ -49,26 +50,30 @@ class MatchMaker:
if not self.waiting_players:
break
async def create_game(self, player1, player2):
async def create_game(self, player1, player2, localgame):
game_id = len(self.active_games) + 1
print(f"- Creating game: #{game_id}")
new_game = Game(game_id, player1, player2)
if localgame:
print(f"- Creating LOCAL game: #{game_id}")
else:
print(f"- Creating MATCH game: #{game_id}")
new_game = Game(game_id, player1, player2, localgame)
self.active_games[game_id] = new_game
await player1.set_game(new_game)
await player2.set_game(new_game)
await self.notify_players(player1, player2, game_id)
if not localgame:
await player2.set_game(new_game)
await self.notify_players(player1, player2, game_id, localgame)
asyncio.create_task(new_game.start_game())
async def create_bot_game(self, player1):
game_id = len(self.active_games) + 1
print(f"- Creating BOT game: #{game_id}")
new_game = Game(game_id, player1, None)
new_game = Game(game_id, player1, None, False)
self.active_games[game_id] = new_game
await player1.set_game(new_game)
await self.notify_players(player1, None, game_id)
await self.notify_players(player1, None, game_id, False)
asyncio.create_task(new_game.start_game())
async def notify_players(self, player1, player2, game_id):
async def notify_players(self, player1, player2, game_id, localgame):
if player2:
await player1.send(json.dumps({
'type': 'game_start',
@ -83,21 +88,20 @@ class MatchMaker:
'player2': player2.user.username
}))
else:
await player1.send(json.dumps({
'type': 'game_start',
'game_id': game_id,
'player1': player1.user.username,
'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
if localgame:
await player1.send(json.dumps({
'type': 'game_start',
'game_id': game_id,
'player1': player1.user.username,
'player2': player1.user2.username
}))
else:
await player1.send(json.dumps({
'type': 'game_start',
'game_id': game_id,
'player1': player1.user.username,
'player2': 'BOT'
}))
# 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,18 @@
# Generated by Django 5.1.1 on 2024-09-10 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('game', '0002_alter_match_winner'),
]
operations = [
migrations.AlterField(
model_name='tournoi',
name='date',
field=models.DateField(auto_now_add=True),
),
]

View File

@ -4,7 +4,6 @@ from django.db import models
from django.contrib.auth.models import User
User.add_to_class('auth_token', models.CharField(max_length=100, null=True, blank=True, unique=True))
# Create your models here.
class Player(models.Model):
name = models.CharField(max_length=100)
@ -26,7 +25,7 @@ class Player(models.Model):
class Tournoi(models.Model):
name = models.CharField(max_length=200)
nbr_player = models.PositiveSmallIntegerField()
date = models.DateField()
date = models.DateField(auto_now_add=True)
winner = models.ForeignKey('Player', on_delete=models.SET_NULL, null=True)
def __str__(self):
@ -55,7 +54,7 @@ class Match(models.Model):
super().clean()
def save(self, *args, **kwargs):
self.clean() # Appel de la méthode clean() avant d'enregistrer
self.clean()
super().save(*args, **kwargs)
def __str__(self):

View File

@ -1,51 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matches List</title>
</head>
<body>
<h1>Matches List</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Player 1</th>
<th>Player 2</th>
<th>Score Player 1</th>
<th>Score Player 2</th>
<th>Winner</th>
<th>Ball Touches Player 1</th>
<th>Ball Touches Player 2</th>
<th>Duration</th>
<th>Date</th>
<th>Is Tournament</th>
<th>Tournament</th>
</tr>
</thead>
<tbody>
{% for match in matches %}
<tr>
<td>{{ match.id }}</td>
<td>{{ match.player1.name }}</td>
<td>{{ match.player2.name }}</td>
<td>{{ match.score_player1 }}</td>
<td>{{ match.score_player2 }}</td>
<td>{{ match.winner.name }}</td>
<td>{{ match.nbr_ball_touch_p1 }}</td>
<td>{{ match.nbr_ball_touch_p2 }}</td>
<td>{{ match.duration }}</td>
<td>{{ match.date }}</td>
<td>{{ match.is_tournoi }}</td>
<td>{{ match.tournoi.name }}</td>
</tr>
{% empty %}
<tr>
<td colspan="12">No matches found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

View File

@ -1,53 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Players List</title>
</head>
<body>
<h1>Players List</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Total Matches</th>
<th>Total Wins</th>
<th>Win Percentage</th>
<th>Average Match Score</th>
<th>Average Opponent Score</th>
<th>Best Score</th>
<th>Average Ball Touches</th>
<th>Total Duration</th>
<th>Average Duration</th>
<th>Participated Tournaments</th>
<th>Won Tournaments</th>
</tr>
</thead>
<tbody>
{% for player in players %}
<tr>
<td>{{ player.id }}</td>
<td>{{ player.name }}</td>
<td>{{ player.total_match }}</td>
<td>{{ player.total_win }}</td>
<td>{{ player.p_win }}</td>
<td>{{ player.m_score_match }}</td>
<td>{{ player.m_score_adv_match }}</td>
<td>{{ player.best_score }}</td>
<td>{{ player.m_nbr_ball_touch }}</td>
<td>{{ player.total_duration }}</td>
<td>{{ player.m_duration }}</td>
<td>{{ player.num_participated_tournaments }}</td>
<td>{{ player.num_won_tournaments }}</td>
</tr>
{% empty %}
<tr>
<td colspan="13">No players found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

View File

@ -0,0 +1,60 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tournament Brackets</title>
<style>
.tournament-bracket {
display: flex;
padding: 20px;
font-family: Arial, sans-serif;
overflow-x: auto;
}
.round {
display: flex;
flex-direction: column;
justify-content: space-around;
margin-right: 40px;
}
.match {
display: flex;
flex-direction: column;
}
.player {
width: 150px;
height: 30px;
line-height: 30px;
background-color: #000000;
border: 1px solid #ffffff;
margin: 2px 0;
padding: 0 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.player.winner {
background-color: #00ff3c;
font-weight: bold;
}
</style>
</head>
<body>
<div class="tournament-bracket">
{% for round in tournament_rounds %}
<div class="round">
{% for match in round %}
<div class="match">
<div class="player {% if match.winner == match.player1 %}winner{% endif %}">
{{ match.player1 }}
</div>
<div class="player {% if match.winner == match.player2 %}winner{% endif %}">
{{ match.player2|default:"BYE" }}
</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</body>
</html>

View File

@ -0,0 +1,20 @@
<!-- pong/tournament_waiting_room.html -->
<div class="tournament-waiting-room">
<h2>Tournament Waiting Room</h2>
<p>Players currently waiting: {{ players_count }}</p>
<p>Minimum players needed to start: {{ min_players_to_start }}</p>
<h3>Players:</h3>
<ul>
{% for player in players %}
<li>{{ player }}</li>
{% endfor %}
</ul>
{% if players_count >= min_players_to_start %}
<button id="start-tournament-btn">Start Tournament</button>
{% else %}
<p>Waiting for more players to join...</p>
{% endif %}
</div>

View File

@ -1,37 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tournaments List</title>
</head>
<body>
<h1>Tournaments List</h1>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Number of Players</th>
<th>Date</th>
<th>Winner</th>
</tr>
</thead>
<tbody>
{% for tournoi in tournois %}
<tr>
<td>{{ tournoi.id }}</td>
<td>{{ tournoi.name }}</td>
<td>{{ tournoi.nbr_player }}</td>
<td>{{ tournoi.date }}</td>
<td>{{ tournoi.winner.name }}</td>
</tr>
{% empty %}
<tr>
<td colspan="5">No tournaments found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

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

@ -0,0 +1,222 @@
# /pong/game/tournament.py
import json
import asyncio
from django.template.loader import render_to_string
import random
from .matchmaking import match_maker
from .game import Game
from .models import Tournoi
from .utils import create_tournament, update_tournament, getlen
from asgiref.sync import sync_to_async
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",
"Shibuya Incident", "Cunning Game", "Elite of the Stars", "Chaku's Disciples"
]
class TournamentMatch(Game):
def __init__(self, game_id, player1, player2, tournament):
# Initialize the parent Game class with the provided parameters
super().__init__(game_id, player1, player2, False)
# Store the current game instance in active games
match_maker.active_games[game_id] = self
# Store the tournament instance
self.tournament = tournament
async def end_game(self, disconnected_player=None):
# Call the parent class's end_game method
await super().end_game(disconnected_player)
# Handle the end of the match in the tournament context
await self.tournament.handle_match_end(self)
if self.game_id in match_maker.active_games:
del match_maker.active_games[self.game_id]
class TournamentMatchMaker:
def __init__(self):
self.waiting_players = []
self.matches = []
self.rounds = []
self.current_round = 0
self.games = 0
self.tournament_state = "waiting" #Can be "waiting", "in_progress", or "ended"
self.name = random.choice(TOURNAMENT_NAMES)
self.final_name = ""
self.tournoi_reg = None
async def add_player(self, player):
if self.tournament_state == "waiting" and player not in self.waiting_players:
self.waiting_players.append(player)
if player:
print(f"User {player.user.username} joins the TOURNAMENT WAITING ROOM")
else:
print("BOT joins the TOURNAMENT WAITING ROOM")
await self.update_waiting_room()
async def update_waiting_room(self):
html = self.generate_waiting_room_html()
for player in self.waiting_players:
await self.send_to_player(player, {
'type': 'update_tournament_waiting_room',
'html': html
})
def generate_waiting_room_html(self):
context = {
'players': [player.user.username if player else 'BYE' for player in self.waiting_players],
'tournament_state': self.tournament_state,
'players_count': len(self.waiting_players),
'min_players_to_start': 3 # You can adjust this number as needed
}
return render_to_string('pong/tournament_waiting_room.html', context)
async def send_to_player(self, player, data):
if player:
await player.send(json.dumps(data))
async def remove_player(self, player):
if player in self.waiting_players:
self.waiting_players.remove(player)
await self.update_waiting_room()
# Tournament start method
async def start_tournament(self):
if len(self.waiting_players) < 2:
return False
if len(self.waiting_players) % 2 == 0:
await self.add_player(None)
self.tournament_state = "in_progress"
random.shuffle(self.waiting_players)
self.current_round = 0
len_tournament = await sync_to_async(getlen)()
self.final_name = self.name + " #" + str(len_tournament + 1)
self.tournoi_reg = await sync_to_async(create_tournament)(self.final_name, len(self.waiting_players))
await self.advance_tournament()
return True
async def advance_tournament(self):
players = self.waiting_players
while len(players) > 1:
self.current_round += 1
print(f"Starting round {self.current_round} with {len(players)} 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
current_round_matches = self.rounds[-1]
while not all(match.ended for match in current_round_matches):
await asyncio.sleep(1) # Wait for 1 second before checking again
# Get winners for the next round
players = self.get_round_winners()
print(f"Round {self.current_round} finished. {len(players)} players advancing.")
# Tournament has ended
await self.update_brackets()
await self.end_tournament(players[0] if players else None)
async def create_matches(self, players):
matches = []
for i in range(0, len(players), 2):
self.games += 1
if i + 1 < len(players):
# Create a new instance of TournamentMatch for this round
match = TournamentMatch(self.games, players[i], players[i + 1], self)
matches.append(match)
else:
# 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
if players[i]:
await players[i].set_game(match)
if i + 1 < len(players):
if players[i + 1]:
await players[i + 1].set_game(match)
self.rounds.append(matches)
self.matches.extend(matches)
async def update_brackets(self):
html = self.generate_bracket_html()
for player in self.waiting_players:
await self.send_to_player(player, {
'type': 'update_brackets',
'html': html
})
def generate_bracket_html(self):
context = {
'tournament_rounds': self.get_tournament_data()
}
return render_to_string('pong/tournament_brackets.html', context)
def get_tournament_data(self):
return [
[
{
'player1': match.player1.user.username if match.player1 else 'BYE',
'player2': match.player2.user.username if match.player2 else 'BYE',
'winner': match.game_state['player1_name'] if match.game_state['player1_score'] > match.game_state['player2_score'] else match.game_state['player2_name'] if match.ended else None,
'score1': match.game_state['player1_score'],
'score2': match.game_state['player2_score']
}
for match in round_matches
]
for round_matches in self.rounds
]
async def start_round_matches(self):
print(f"Starting TOURNAMENT round #{self.current_round}")
for match in self.rounds[-1]:
if match.player1 and match.player2:
await match_maker.notify_players(match.player1, match.player2, match.game_id, False)
asyncio.create_task(match.start_game())
elif match.player1:
# Handle BYE match
await match_maker.notify_players(match.player1, match.player2, match.game_id, False)
#asyncio.create_task(match.start_game())
match.game_state['player1_score'] = 3
match.game_state['player2_score'] = 0
await match.end_game()
def get_round_winners(self):
winners = []
for match in self.rounds[-1]:
if match.ended:
winner = match.player1 if match.game_state['player1_score'] > match.game_state['player2_score'] else match.player2
#if winner:
winners.append(winner)
return winners
async def end_tournament(self, winner):
self.tournament_state = "ended"
winner_username = winner.user.username if winner else "No winner"
print(f"The TOURNAMENT winner is {winner_username}")
for player in self.waiting_players:
await self.send_to_player(player, {
'type': 'tournament_end',
'winner': winner_username
})
await sync_to_async(update_tournament)(self.final_name, winner_username)
# Reset tournament state
self.waiting_players = []
self.matches = []
self.rounds = []
self.current_round = 0
self.games = 0
async def handle_match_end(self, match):
await self.update_brackets()
# Instance of the class
tournament_match_maker = TournamentMatchMaker()

View File

@ -2,11 +2,8 @@
from django.urls import path, include
from . import views
from .views import player_list, tournoi_list, match_list
from rest_framework.routers import DefaultRouter
from .views import match_list_json
from .views import player_list_json
from .views import match_list_json, player_list_json, tournoi_list_json
urlpatterns = [
@ -14,9 +11,8 @@ urlpatterns = [
path('check_user_exists/', views.check_user_exists, name='check_user_exists'),
path('register_user/', views.register_user, name='register_user'),
path('authenticate_user/', views.authenticate_user, name='authenticate_user'),
path('players/', player_list, name='player_list'),
path('matches/', match_list, name='match_list'),
path('tournois/', tournoi_list, name='tournoi_list'),
path('web3/', views.read_data, name='read_data'),
path('api/match_list/', match_list_json, name='match_list_json'),
path('api/player_list/', player_list_json, name='player_list_json'),
path('api/tournoi_list/', tournoi_list_json, name='tournoi_list_json')
]

View File

@ -5,33 +5,38 @@ from django.db.models import Max, Sum, F
from datetime import timedelta
from channels.db import database_sync_to_async
async def endfortheouche(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament):
# Check if player p1 exists, if not create
if not await database_sync_to_async(Player.objects.filter(name=p1).exists)():
player_1 = await create_player(p1)
print("############# PLAYER DONE")
def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament):
try:
player_1 = get_or_create_player(p1)
player_2 = get_or_create_player(p2)
create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
update_player_statistics(p1)
update_player_statistics(p2)
except Exception as e:
print(f"Error in endfortheouche: {e}")
def get_player_by_name(name):
exists = Player.objects.filter(name=name).exists()
return exists
def get_player(name):
return Player.objects.get(name=name)
def get_or_create_player(name):
player_exists = get_player_by_name(name)
if not player_exists:
player = create_player(name)
return player
else:
player_1 = await database_sync_to_async(Player.objects.get)(name=p1)
player = get_player(name)
return player
# Check if player p2 exists, if not create
if not await database_sync_to_async(Player.objects.filter(name=p2).exists)():
player_2 = await create_player(p2)
print("############# PLAYER DONE")
else:
player_2 = await database_sync_to_async(Player.objects.get)(name=p2)
# create Match
print("############# BEFORE MATCH")
await create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
print("############# AFTER DONE")
# Update data p1 et p2
await uptdate_player_statistics(p1)
print("############# END STAT P1")
await uptdate_player_statistics(p2)
@database_sync_to_async
def create_player(
name,
total_match=0,
@ -46,33 +51,29 @@ def create_player(
num_participated_tournaments=0,
num_won_tournaments=0
):
if Player.objects.filter(name=name).exists():
raise ValueError(f"A player with the name '{name}' already exists.")
player = Player(
name=name,
total_match = total_match,
total_win = total_win,
p_win = p_win,
m_score_match = m_score_match,
m_score_adv_match = m_score_adv_match,
best_score = best_score,
m_nbr_ball_touch = m_nbr_ball_touch,
total_duration = total_duration,
m_duration = m_duration,
num_participated_tournaments = num_participated_tournaments,
num_won_tournaments = num_won_tournaments
total_match=total_match,
total_win=total_win,
p_win=p_win,
m_score_match=m_score_match,
m_score_adv_match=m_score_adv_match,
best_score=best_score,
m_nbr_ball_touch=m_nbr_ball_touch,
total_duration=total_duration,
m_duration=m_duration,
num_participated_tournaments=num_participated_tournaments,
num_won_tournaments=num_won_tournaments
)
player.save()
return player
@database_sync_to_async
def create_tournoi(name, nbr_player, date, winner):
tournoi = Tournoi(name=name, nbr_player=nbr_player, date=date, winner=winner)
tournoi.save()
return tournoi
@database_sync_to_async
def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration, is_tournoi, tournoi):
match = Match(
player1=player1,
@ -96,22 +97,16 @@ def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_
match.save()
return match
@database_sync_to_async
def uptdate_player_statistics(player_name):
print("############# BEG STAT P")
def update_player_statistics(player_name):
player = get_object_or_404(Player, name=player_name)
# Filtrer les matchs où le joueur est joueur 1 ou joueur 2
print("############# HERE")
matches_as_player1 = Match.objects.filter(player1=player)
matches_as_player2 = Match.objects.filter(player2=player)
print("############# ACTUALLY, IT'S GOOD")
# Calculer les statistiques
total_match = matches_as_player1.count() + matches_as_player2.count()
# avoid dividing by 0
if total_match == 0:
# Eviter la division par zéro
player.total_match = total_match
player.total_win = 0
player.p_win = 0
@ -127,9 +122,9 @@ def uptdate_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__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)
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
@ -151,15 +146,14 @@ def uptdate_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
best_score = max(best_score_as_player1, best_score_as_player2)
# Mettre à jour les champs du joueur
player.total_match = total_match
player.total_win = total_win
player.p_win = p_win
@ -169,50 +163,34 @@ def uptdate_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()
print("CHAKU IS THE BEST")
def get_player_p_win(player_name):
# Rechercher le joueur par son nom
player = get_object_or_404(Player, name=player_name)
# Retourner la valeur de p_win
return player.p_win
""" def complete_match(match_id, score_player1, score_player2, nbr_ball_touch_p1, nbr_ball_touch_p2, duration):
try:
match = Match.objects.get(id=match_id)
except Match.DoesNotExist:
raise ValidationError(f"Match with id {match_id} does not exist")
match.score_player1 = score_player1
match.score_player2 = score_player2
match.nbr_ball_touch_p1 = nbr_ball_touch_p1
match.nbr_ball_touch_p2 = nbr_ball_touch_p2
match.duration = duration
if score_player1 > score_player2:
match.winner = match.player1
elif score_player2 > score_player1:
match.winner = match.player2
else:
match.winner = None
match.save()
return match """
""" def complete_tournoi(tournoi_id, player):
try:
tournoi = Tournoi.objects.get(id = tournoi_id)
except Tournoi.DoesNotExist:
raise ValidationError(f"Tournoi with id {tournoi_id} does not exist")
tournoi.winner = player
def create_tournament(name, nbr_player):
print("tournoi created!!!")
tournoi=Tournoi(name=name, nbr_player=nbr_player, winner=None)
tournoi.save()
print(f"tournoi name : {tournoi.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
return tournoi
def update_tournament(name_tournoi, winner_name):
tournoi = get_object_or_404(Tournoi, name=name_tournoi)
winner_p = get_object_or_404(Player, name=winner_name)
print(f"in update tourna - tournoi name : {tournoi.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
print(f"in update tourna - winner is : {winner_p.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
tournoi.winner = winner_p
print(f"in update tourna - TOURNOI winner is : {tournoi.winner.name} *******!*!*!*!**!*!**!*!*!*!*!*!*!*!*!*")
tournoi.save()
return tournoi """
def getlen():
return Tournoi.objects.count()

View File

@ -1,10 +1,6 @@
# /pong/game/views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
from django.core.exceptions import ObjectDoesNotExist
from .models import Player, Tournoi, Match
from .utils import create_player, create_tournoi, create_match
@ -12,12 +8,24 @@ from django.http import JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.views.decorators.csrf import csrf_exempt
""" from .serializers import MatchSerializer """
from rest_framework import viewsets
import json
import uuid
def index(request):
return render(request, 'index.html')
@csrf_exempt
def check_user_exists(request):
if request.method == 'POST':
data = json.loads(request.body)
username = data.get('username')
if User.objects.filter(username=username).exists():
return JsonResponse({'exists': True})
return JsonResponse({'exists': False})
return JsonResponse({'error': 'Invalid request method'}, status=400)
@csrf_exempt
def register_user(request):
if request.method == 'POST':
@ -31,16 +39,6 @@ def register_user(request):
return JsonResponse({'registered': False, 'error': 'User already exists'})
return JsonResponse({'error': 'Invalid request method'}, status=400)
@csrf_exempt
def check_user_exists(request):
if request.method == 'POST':
data = json.loads(request.body)
username = data.get('username')
if User.objects.filter(username=username).exists():
return JsonResponse({'exists': True})
return JsonResponse({'exists': False})
return JsonResponse({'error': 'Invalid request method'}, status=400)
@csrf_exempt
def authenticate_user(request):
if request.method == 'POST':
@ -69,25 +67,8 @@ def get_or_create_token(user):
break
return user.auth_token
####################### THEOUCHE PART ############################
def player_list(request):
players = Player.objects.all()
return render(request, 'pong/player_list.html', {'players': players})
def match_list(request):
matches = Match.objects.select_related('player1', 'player2', 'winner', 'tournoi').all()
return render(request, 'pong/match_list.html', {'matches': matches})
def tournoi_list(request):
tournois = Tournoi.objects.select_related('winner').all()
return render(request, 'pong/tournoi_list.html', {'tournois': tournois})
from django.http import JsonResponse
def match_list_json(request):
matches = Match.objects.select_related('player1', 'player2', 'winner', 'tournoi').all()
matches = Match.objects.all()
data = {
'matches': list(matches.values(
'id', 'player1__name', 'player2__name', 'score_player1', 'score_player2',
@ -98,10 +79,8 @@ def match_list_json(request):
return JsonResponse(data)
def player_list_json(request):
# Récupère tous les joueurs
players = Player.objects.all()
# Crée un dictionnaire avec les informations des joueurs
data = {
'players': list(players.values(
'id', 'name', 'total_match', 'total_win', 'p_win',
@ -110,9 +89,81 @@ def player_list_json(request):
'num_participated_tournaments', 'num_won_tournaments'
))
}
return JsonResponse(data)
# Renvoie les données en JSON
def tournoi_list_json(request):
tournois = Tournoi.objects.all()
data = {
'tournois': list(tournois.values(
'id', 'name', 'nbr_player', 'date', 'winner'
))
}
return JsonResponse(data)
####################### THEOUCHE PART ############################
from web3 import Web3
provider = Web3.HTTPProvider("https://sepolia.infura.io/v3/60e51df7c97c4f4c8ab41605a4eb9907")
web3 = Web3(provider)
eth_gas_price = web3.eth.gas_price/1000000000
print(eth_gas_price)
contract_address = "0x078D04Eb6fb97Cd863361FC86000647DC876441B"
contract_abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"uint256","name":"_timecode","type":"uint256"},{"internalType":"uint256","name":"_participantCount","type":"uint256"},{"internalType":"string[]","name":"_playerPseudonyms","type":"string[]"},{"internalType":"string[]","name":"_finalOrder","type":"string[]"}],"name":"addTournament","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllTournaments","outputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"timecode","type":"uint256"},{"internalType":"uint256","name":"participantCount","type":"uint256"},{"internalType":"string[]","name":"playerPseudonyms","type":"string[]"},{"internalType":"string[]","name":"finalOrder","type":"string[]"}],"internalType":"struct PongTournament.Tournament[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_id","type":"uint256"}],"name":"getTournament","outputs":[{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"timecode","type":"uint256"},{"internalType":"uint256","name":"participantCount","type":"uint256"},{"internalType":"string[]","name":"playerPseudonyms","type":"string[]"},{"internalType":"string[]","name":"finalOrder","type":"string[]"}],"internalType":"struct PongTournament.Tournament","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tournamentCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tournaments","outputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"timecode","type":"uint256"},{"internalType":"uint256","name":"participantCount","type":"uint256"}],"stateMutability":"view","type":"function"}]
contract = web3.eth.contract(address=contract_address, abi=contract_abi)
def read_data(request):
# Créer une instance du contrat
# Appeler une fonction du contrat pour obtenir tous les tournois
tournaments = contract.functions.getAllTournaments().call()
# Afficher les résultats
json_data = []
for tournament in tournaments:
tournament_data = []
for item in tournament:
print(f"{item}")
tournament_data.append(item)
json_data.append(tournament_data)
# Retourner le JSON comme réponse HTTP
# print(f"Tournament ID: {tournament[0]}")
# print(f"Name: {tournament[1]}")
# print(f"Timecode: {tournament[2]}")
# print(f"Participant Count: {tournament[3]}")
# print(f"Player Pseudonyms: {', '.join(tournament[4])}")
# print(f"Final Order: {', '.join(tournament[5])}")
print("-----------------------------")
return JsonResponse(json_data, safe=False)
def write_data(request):
# addTournament(string,uint256,uint256,string[],string[])
# # Configuration de la transaction pour la fonction store
# account = "0x66CeBE2A1F7dae0F6AdBAad2c15A56A9121abfEf"
# private_key = "beb16ee3434ec5abec8b799549846cc04443c967b8d3643b943e2e969e7d25be"
# nonce = web3.eth.get_transaction_count(account)
# transaction = contract.functions.addTournament("test",1721830559,6,["aaudeber", "tlorne", "ocassany", "yestello", "jcheca", "toto"],["toto", "jcheca", "yestello", "tlorne", "ocassany", "aaudeber"]).build_transaction({
# 'chainId': 11155111, # ID de la chaîne Sepolia
# 'gas': 2000000,
# 'gasPrice': web3.to_wei(eth_gas_price, 'gwei'),
# 'nonce': nonce
# })
# # Signature de la transaction
# signed_txn = web3.eth.account.sign_transaction(transaction, private_key)
# # Envoi de la transaction
# tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
# print("Transaction hash:", web3.to_hex(tx_hash))
# # Attente de la confirmation de la transaction
# tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
# print("Transaction receipt:", tx_receipt)
print("-----------------------------")

View File

@ -6,8 +6,9 @@ Django settings for pong project.
Generated by 'django-admin startproject' using Django 3.2.
"""
from pathlib import Path
import os
import logging.config
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@ -34,8 +35,8 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels', # Add Django Channels
'pong.game', # Your game app
'channels',
'pong.game',
'rest_framework'
]
@ -67,7 +68,7 @@ TEMPLATES = [
},
]
ASGI_APPLICATION = 'pong.asgi.application' # Add ASGI application
ASGI_APPLICATION = 'pong.asgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
@ -134,3 +135,38 @@ CHANNEL_LAYERS = {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
LOGGING = {
'version': 1, # The version of the logging configuration schema
'disable_existing_loggers': False, # Allows existing loggers to keep logging
'formatters': { # Defines how log messages will be formatted
'json': {
'()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
# Formatter that outputs logs in JSON format, which is ideal for ingestion by Logstash.
},
'default': {
'format': '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s',
# This is a basic text formatter with timestamp, log level, logger name, line number, and the actual message.
},
},
'handlers': { # Handlers determine where the log messages are sent
'file': {
'level': 'INFO', # Minimum log level to be handled (INFO and above)
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'logs/django.log'), # The file where logs will be saved
'formatter': 'json', # Uses the JSON formatter defined above
},
'console': {
'level': 'DEBUG', # Minimum log level to be handled (DEBUG and above)
'class': 'logging.StreamHandler',
'formatter': 'default', # Uses the default text formatter
},
},
'loggers': { # Loggers are the actual log streams that get configured
'django': { # The Django logger catches all messages sent by the Django framework
'handlers': ['file', 'console'], # Sends logs to both the file and the console
'level': 'DEBUG', # Minimum log level to be logged
'propagate': True, # If True, messages will be passed to the parent loggers as well
},
},
}

397
pong/static/burger.js Normal file
View File

@ -0,0 +1,397 @@
document.addEventListener('DOMContentLoaded', () => {
const menuButton = document.querySelector('.burger-menu');
const dropdownMenu = document.getElementById('dropdown-menu');
const playerList = document.getElementById('player-list');
const matchList = document.getElementById('match-list');
const tournoiList = document.getElementById('tournoi-list');
const blockchainList = document.getElementById('blockchain-list');
const logo = document.querySelector('.logo');
menuButton.addEventListener('click', toggleMenu);
function toggleMenu() {
console.log('Menu toggled');
if (dropdownMenu.style.display === "block") {
dropdownMenu.style.display = "none";
hideAllTables();
} else {
dropdownMenu.style.display = "block";
}
}
function hideAllTables(){
if (playerList) playerList.style.display = 'none';
if (matchList) matchList.style.display = 'none';
if (tournoiList) tournoiList.style.display = 'none';
if (blockchainList) blockchainList.style.display = 'none';
logo.style.display = 'block';
}
const links = document.querySelectorAll('#dropdown-menu a');
links.forEach(link => {
link.addEventListener('click', (event) => {
event.preventDefault();
const tableId = link.getAttribute('data-table');
showTable(tableId);
});
});
function showTable(tableId) {
hideAllTables();
logo.style.display = 'none';
if (tableId === 'player-list') {
playerList.style.display = 'block';
fetchPlayers();
} else if (tableId === 'match-list') {
matchList.style.display = 'block';
fetchMatches();
} else if (tableId === 'tournoi-list') {
tournoiList.style.display = 'block';
fetchTournois();
} else if (tableId === 'blockchain-list') {
console.log('Opening external page in a new tab');
window.open('https://sepolia.etherscan.io/address/0x078d04eb6fb97cd863361fc86000647dc876441b', '_blank');
}
if (dropdownMenu) {
dropdownMenu.style.display = 'none';
}
}
function fetchMatches() {
console.log('Fetching matches...');
fetch('/api/match_list/')
.then(response => response.json())
.then(data => {
if (data.matches) {
displayMatches(data.matches);
}
})
.catch(error => console.error('Error fetching match data:', error));
}
function fetchPlayers(){
console.log('Fetching players...');
fetch('/api/player_list/')
.then(response => response.json())
.then(data => {
if (data.players) {
displayPlayers(data.players);
}
})
.catch(error => console.error('Error fetching match data:', error));
}
function fetchTournois(){
console.log('Fetching tournois...');
fetch('/api/tournoi_list/')
.then(response => response.json())
.then(data => {
if (data.tournois) {
displayTournois(data.tournois);
}
})
.catch(error => console.error('Error fetching match data:', error));
}
function displayMatches(matches) {
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 => {
row.innerHTML = `
<td>${match.id}</td>
<td>${match.player1__name}</td>
<td>${match.player2__name}</td>
<td>${match.score_player1}</td>
<td>${match.score_player2}</td>
<td>${match.winner__name}</td>
<td>${match.nbr_ball_touch_p1}</td>
<td>${match.nbr_ball_touch_p2}</td>
<td>${match.duration}</td>
<td>${match.date}</td>
<td>${match.is_tournoi}</td>
<td>${match.tournoi__name}</td>
`;
matchListBody.appendChild(row);
});
} else {
row.innerHTML = `
<td colspan="12">No matches found.</td>
`;
matchListBody.appendChild(row);
}
}
function displayPlayers(players) {
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 => {
row.innerHTML = `
<td>${player.id}</td>
<td>${player.name}</td>
<td>${player.total_match}</td>
<td>${player.total_win}</td>
<td>${player.p_win}</td>
<td>${player.m_score_match}</td>
<td>${player.m_score_adv_match}</td>
<td>${player.best_score}</td>
<td>${player.m_nbr_ball_touch}</td>
<td>${player.total_duration}</td>
<td>${player.m_duration}</td>
<td>${player.num_participated_tournaments}</td>
<td>${player.num_won_tournaments}</td>
`;
playersListBody.appendChild(row);
});
} else {
row.innerHTML = `
<td colspan="12">No matches found.</td>
`
playersListBody.appendChild(row);
}
}
function displayTournois(tournois) {
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 => {
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>
`;
tournoisListBody.appendChild(row);
});
} else {
row.innerHTML = `
<td colspan="12">No matches found.</td>
`
tournoisListBody.appendChild(row);
}
}
document.getElementById('search-player').addEventListener('input', filterPlayers);
document.getElementById('search-match-player').addEventListener('input', filterMatches);
document.getElementById('search-match-date').addEventListener('input', filterMatches);
function filterPlayers() {
const searchValue = document.getElementById('search-player').value.toLowerCase();
const playersListBody = document.querySelector('#player-list tbody');
const rows = playersListBody.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const nameCell = rows[i].getElementsByTagName('td')[1];
if (nameCell) {
const nameValue = nameCell.textContent || nameCell.innerText;
if (nameValue.toLowerCase().indexOf(searchValue) > -1 ) {
rows[i].style.display = '';
} else {
rows[i].style.display = 'none';
}
}
}
}
function filterMatches() {
const playerSearchValue = document.getElementById('search-match-player').value.toLowerCase();
const dateSearchValue = document.getElementById('search-match-date').value;
const matchListBody = document.querySelector('#match-list tbody');
const rows = matchListBody.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const player1Cell = rows[i].getElementsByTagName('td')[1];
const player2Cell = rows[i].getElementsByTagName('td')[2];
const dateCell = rows[i].getElementsByTagName('td')[9];
let playerMatch = true;
if (playerSearchValue) {
const player1Value = player1Cell.textContent || player1Cell.innerText;
const player2Value = player2Cell.textContent || player2Cell.innerText;
playerMatch = player1Value.toLowerCase().indexOf(playerSearchValue) > -1 ||
player2Value.toLowerCase().indexOf(playerSearchValue) > -1;
}
let dateMatch = true;
if (dateSearchValue) {
const dateValue = dateCell.textContent || dateCell.innerText;
dateMatch = dateValue.startsWith(dateSearchValue);
}
if (playerMatch && dateMatch) {
rows[i].style.display = '';
} else {
rows[i].style.display = 'none';
}
}
}
document.getElementById('generate-player-chart').addEventListener('click', generatePlayerChart);
document.getElementById('generate-match-chart').addEventListener('click', generateMatchLinePlot);
function generatePlayerChart() {
if (document.getElementById('player-chart').style.display === 'block'){
document.getElementById('player-chart').style.display = 'none';
return ;
}
if (logo.style.display === 'block'){
logo.style.display = 'none';
}
const rows = document.querySelectorAll('#player-list tbody tr');
const playerNames = [];
const totalMatches = [];
const totalWins = [];
rows.forEach(row => {
const cells = row.getElementsByTagName('td');
playerNames.push(cells[1].innerText);
totalMatches.push(parseInt(cells[2].innerText));
totalWins.push(parseInt(cells[3].innerText));
});
const ctx = document.getElementById('player-chart').getContext('2d');
document.getElementById('player-chart').style.display = 'block';
new Chart(ctx, {
type: 'bar',
data: {
labels: playerNames,
datasets: [
{ label: 'Total Matches', data: totalMatches, backgroundColor: 'rgba(75, 192, 192, 0.6)' },
{ label: 'Total Wins', data: totalWins, backgroundColor: 'rgba(54, 162, 235, 0.6)' },
]
},
options: {
scales: {
x: {
ticks: {
color: '#00ffff'
}
},
y: {
beginAtZero: true,
ticks: {
color: '#00ffff'
}
}
}
}
});
}
function generateMatchLinePlot() {
if (document.getElementById('match-chart').style.display === 'block'){
document.getElementById('match-chart').style.display = 'none';
return ;
}
const rows = document.querySelectorAll('#match-list tbody tr');
const playerWins = {};
const dates = [];
rows.forEach(row => {
const cells = row.getElementsByTagName('td');
const winner = cells[5].innerText;
const date = cells[9].innerText;
if (!dates.includes(date)) {
dates.push(date);
}
if (!playerWins[winner]) {
playerWins[winner] = [];
}
let existingEntry = playerWins[winner].find(entry => entry.date === date);
if (existingEntry) {
existingEntry.wins += 1;
}
else {
let lastWinCount = playerWins[winner].length > 0 ? playerWins[winner][playerWins[winner].length - 1].wins : 0;
playerWins[winner].push({ date: date, wins: lastWinCount + 1 });
}
});
const datasets = Object.keys(playerWins).map(player => {
return {
label: player,
data: playerWins[player].map(entry => ({ x: entry.date, y: entry.wins })),
fill: false,
borderColor: getRandomColor(),
tension: 0.1
};
});
const ctx = document.getElementById('match-chart').getContext('2d');
document.getElementById('match-chart').style.display = 'block';
new Chart(ctx, {
type: 'line',
data: {
labels: dates.sort(),
datasets: datasets
},
options: {
scales: {
x: {
type: 'time',
time: {
parser: 'YYYY-MM-DD',
unit: 'day',
tooltipFormat: 'll'
},
title: {
display: true,
text: 'Date'
},
ticks: {
color: '#00ffff'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Nombre de Victoires Cumulées'
},
ticks: {
color: '#00ffff'
}
}
}
}
});
}
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
});

7
pong/static/flags/de.svg Executable file
View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
<defs/>
<path id="black_stripe" fill="#000" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25"/>
<path id="red_stripe" fill="#D00" d="M8,419.25 C178.83,334.03 349.03,364.83 521.26,391.28 C676.47,415.12 833.42,435.85 992,356.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,419.25"/>
<path id="gold_stripe" fill="#FFCE00" d="M8,643.25 C178.83,558.03 349.03,588.83 521.26,615.28 C676.47,639.12 833.42,659.85 992,580.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,643.25"/>
<path fill="#1A1A1A" opacity="0.2" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25 M39.25,214.64 L39.25,819.14 C345.81,690.88 650.43,915.18 960.75,785.36 L960.75,180.86 C654.19,309.12 349.57,84.82 39.25,214.64"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

712
pong/static/flags/es.svg Executable file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 415 KiB

7
pong/static/flags/fr.svg Executable file
View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
<defs/>
<path fill="#ED2939" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25"/>
<path fill="#fff" d="M8,195.25 C225.32,86.83 440.27,166.96 664,185.41 L664,857.41 C448.6,839.65 229.72,756.65 8,867.25 L8,195.25"/>
<path fill="#002395" d="M8,195.25 C116.32,141.21 224.41,133.48 336,142.59 L336,814.59 C227.91,805.77 119.34,811.71 8,867.25 L8,195.25"/>
<path fill="#1A1A1A" opacity="0.2" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25 M39.25,214.64 L39.25,819.14 C345.81,690.88 650.43,915.18 960.75,785.36 L960.75,180.86 C654.19,309.12 349.57,84.82 39.25,214.64"/>
</svg>

After

Width:  |  Height:  |  Size: 946 B

7
pong/static/flags/it.svg Executable file
View File

@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
<defs/>
<path fill="#009246" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25"/>
<path fill="#fff" d="M336,142.59 C551.4,160.35 770.28,243.35 992,132.75 L992,804.75 C774.68,913.17 559.73,833.04 336,814.59 L336,142.59"/>
<path fill="#ce2b37" d="M664,185.41 C772.09,194.23 880.66,188.29 992,132.75 L992,804.75 C883.68,858.79 775.59,866.52 664,857.41 L664,185.41"/>
<path fill="#1A1A1A" opacity="0.2" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25 M39.25,214.64 L39.25,819.14 C345.81,690.88 650.43,915.18 960.75,785.36 L960.75,180.86 C654.19,309.12 349.57,84.82 39.25,214.64"/>
</svg>

After

Width:  |  Height:  |  Size: 959 B

57
pong/static/flags/us.svg Executable file
View File

@ -0,0 +1,57 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
<defs/>
<path fill="#b22234" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25"/>
<path fill="#fff" d="M8,246.94 C178.83,161.72 349.03,192.52 521.26,218.97 C676.47,242.82 833.42,263.54 992,184.44 L992,236.13 C821.17,321.36 650.97,290.56 478.74,264.1 C323.53,240.26 166.58,219.53 8,298.63 L8,246.94 M992,339.52 C821.17,424.74 650.97,393.94 478.74,367.49 C323.53,343.65 166.58,322.92 8,402.02 L8,350.33 C178.83,265.1 349.03,295.91 521.26,322.36 C676.47,346.2 833.42,366.93 992,287.83 L992,339.52 M8,453.71 C178.83,368.49 349.03,399.29 521.26,425.74 C676.47,449.58 833.42,470.31 992,391.21 L992,442.9 C821.17,528.13 650.97,497.32 478.74,470.87 C323.53,447.03 166.58,426.3 8,505.4 L8,453.71 M992,546.29 C821.17,631.51 650.97,600.71 478.74,574.26 C323.53,550.42 166.58,529.69 8,608.79 L8,557.1 C178.83,471.87 349.03,502.68 521.26,529.13 C676.47,552.97 833.42,573.7 992,494.6 L992,546.29 M8,660.48 C178.83,575.26 349.03,606.06 521.26,632.51 C676.47,656.35 833.42,677.08 992,597.98 L992,649.67 C821.17,734.9 650.97,704.09 478.74,677.64 C323.53,653.8 166.58,633.07 8,712.17 L8,660.48 M992,753.06 C821.17,838.28 650.97,807.48 478.74,781.03 C323.53,757.18 166.58,736.46 8,815.56 L8,763.87 C178.83,678.64 349.03,709.44 521.26,735.9 C676.47,759.74 833.42,780.47 992,701.37 L992,753.06"/>
<path fill="#3c3b6e" d="M8,195.25 C138.03,130.38 267.66,132.43 401.6,149.63 L401.6,511.47 C272,494.84 141.49,490.5 8,557.1 L8,195.25"/>
<path id="s" fill="#fff" d="M40.8,195.75 L50.17,229.37 C42.07,224.93 33.98,220.71 25.64,216.63 C35.65,212.1 45.65,207.94 55.96,204.02 L31.43,237.16 L40.8,195.75"/>
<path fill="#fff" d="M40.8,268.12 L50.17,301.74 C42.07,297.29 33.98,293.08 25.64,289 C35.65,284.47 45.65,280.3 55.96,276.39 L31.43,309.53 L40.8,268.12"/>
<path fill="#fff" d="M40.8,340.49 L50.17,374.11 C42.07,369.66 33.98,365.45 25.64,361.37 C35.65,356.84 45.65,352.67 55.96,348.76 L31.43,381.9 L40.8,340.49"/>
<path fill="#fff" d="M40.8,412.86 L50.17,446.48 C42.07,442.03 33.98,437.82 25.64,433.74 C35.65,429.2 45.65,425.04 55.96,421.13 L31.43,454.27 L40.8,412.86"/>
<path fill="#fff" d="M40.8,485.23 L50.17,518.85 C42.07,514.4 33.98,510.19 25.64,506.11 C35.65,501.57 45.65,497.41 55.96,493.5 L31.43,526.64 L40.8,485.23"/>
<path fill="#fff" d="M73.6,219.6 L82.97,253.95 C74.87,248.88 66.78,244.03 58.44,239.27 C68.45,235.55 78.45,232.18 88.76,229.04 L64.23,260.27 L73.6,219.6"/>
<path fill="#fff" d="M73.6,291.97 L82.97,326.32 C74.87,321.25 66.78,316.4 58.44,311.64 C68.45,307.92 78.45,304.54 88.76,301.41 L64.23,332.64 L73.6,291.97"/>
<path fill="#fff" d="M73.6,364.34 L82.97,398.69 C74.87,393.62 66.78,388.77 58.44,384.01 C68.45,380.29 78.45,376.91 88.76,373.78 L64.23,405.01 L73.6,364.34"/>
<path fill="#fff" d="M73.6,436.71 L82.97,471.06 C74.87,465.99 66.78,461.14 58.44,456.38 C68.45,452.66 78.45,449.28 88.76,446.15 L64.23,477.38 L73.6,436.71"/>
<path fill="#fff" d="M106.4,173.57 L115.77,208.59 C107.67,202.95 99.58,197.5 91.24,192.11 C101.25,189.15 111.25,186.5 121.56,184.09 L97.03,213.55 L106.4,173.57"/>
<path fill="#fff" d="M106.4,245.94 L115.77,280.96 C107.67,275.32 99.58,269.87 91.24,264.48 C101.25,261.52 111.25,258.87 121.56,256.46 L97.03,285.91 L106.4,245.94"/>
<path fill="#fff" d="M106.4,318.31 L115.77,353.33 C107.67,347.69 99.58,342.24 91.24,336.85 C101.25,333.89 111.25,331.24 121.56,328.83 L97.03,358.28 L106.4,318.31"/>
<path fill="#fff" d="M106.4,390.68 L115.77,425.7 C107.67,420.05 99.58,414.61 91.24,409.22 C101.25,406.26 111.25,403.61 121.56,401.2 L97.03,430.65 L106.4,390.68"/>
<path fill="#fff" d="M106.4,463.05 L115.77,498.07 C107.67,492.42 99.58,486.98 91.24,481.59 C101.25,478.63 111.25,475.98 121.56,473.57 L97.03,503.02 L106.4,463.05"/>
<path fill="#fff" d="M139.2,202.2 L148.57,237.84 L124.04,219.7 C134.05,217.44 144.05,215.46 154.36,213.71 L129.83,241.54 L139.2,202.2"/>
<path fill="#fff" d="M139.2,274.57 L148.57,310.21 L124.04,292.07 C134.05,289.81 144.05,287.83 154.36,286.08 L129.83,313.91 L139.2,274.57"/>
<path fill="#fff" d="M139.2,346.94 L148.57,382.58 L124.04,364.44 C134.05,362.17 144.05,360.2 154.36,358.45 L129.83,386.28 L139.2,346.94"/>
<path fill="#fff" d="M139.2,419.3 L148.57,454.95 L124.04,436.81 C134.05,434.54 144.05,432.57 154.36,430.82 L129.83,458.65 L139.2,419.3"/>
<path fill="#fff" d="M172,160.56 L181.37,196.76 L156.84,177.12 C166.85,175.49 176.85,174.12 187.16,172.98 L162.63,199.32 L172,160.56"/>
<path fill="#fff" d="M172,232.92 L181.37,269.13 L156.84,249.48 C166.85,247.85 176.85,246.49 187.16,245.35 L162.63,271.68 L172,232.92"/>
<path fill="#fff" d="M172,305.29 L181.37,341.5 L156.84,321.85 C166.85,320.22 176.85,318.86 187.16,317.72 L162.63,344.05 L172,305.29"/>
<path fill="#fff" d="M172,377.66 L181.37,413.87 L156.84,394.22 C166.85,392.59 176.85,391.23 187.16,390.09 L162.63,416.42 L172,377.66"/>
<path fill="#fff" d="M172,450.03 L181.37,486.24 L156.84,466.59 C166.85,464.96 176.85,463.6 187.16,462.45 L162.63,488.79 L172,450.03"/>
<path fill="#fff" d="M204.8,193.19 L214.17,229.91 L189.64,208.89 C199.65,207.84 209.65,207.03 219.96,206.43 L195.43,231.43 L204.8,193.19"/>
<path fill="#fff" d="M204.8,265.56 L214.17,302.28 L189.64,281.26 C199.65,280.21 209.65,279.4 219.96,278.8 L195.43,303.8 L204.8,265.56"/>
<path fill="#fff" d="M204.8,337.93 L214.17,374.65 L189.64,353.63 C199.65,352.58 209.65,351.77 219.96,351.17 L195.43,376.17 L204.8,337.93"/>
<path fill="#fff" d="M204.8,410.3 L214.17,447.02 L189.64,426 C199.65,424.95 209.65,424.14 219.96,423.54 L195.43,448.53 L204.8,410.3"/>
<path fill="#fff" d="M237.6,155.18 L246.97,192.35 L222.44,170.11 C232.45,169.58 242.45,169.27 252.76,169.15 L228.23,192.94 L237.6,155.18"/>
<path fill="#fff" d="M237.6,227.55 L246.97,264.72 L222.44,242.48 C232.45,241.95 242.45,241.63 252.76,241.52 L228.23,265.31 L237.6,227.55"/>
<path fill="#fff" d="M237.6,299.92 L246.97,337.09 L222.44,314.85 C232.45,314.32 242.45,314 252.76,313.89 L228.23,337.68 L237.6,299.92"/>
<path fill="#fff" d="M237.6,372.29 L246.97,409.46 L222.44,387.22 C232.45,386.69 242.45,386.37 252.76,386.26 L228.23,410.05 L237.6,372.29"/>
<path fill="#fff" d="M237.6,444.66 L246.97,481.83 L222.44,459.59 C232.45,459.06 242.45,458.74 252.76,458.63 L228.23,482.42 L237.6,444.66"/>
<path fill="#fff" d="M270.4,191.06 L279.77,228.64 L255.24,205.31 C265.25,205.25 275.25,205.37 285.56,205.67 L261.03,228.41 L270.4,191.06"/>
<path fill="#fff" d="M270.4,263.43 L279.77,301 L255.24,277.68 C265.25,277.61 275.25,277.74 285.56,278.04 L261.03,300.78 L270.4,263.43"/>
<path fill="#fff" d="M270.4,335.8 L279.77,373.37 L255.24,350.05 C265.25,349.98 275.25,350.11 285.56,350.41 L261.03,373.15 L270.4,335.8"/>
<path fill="#fff" d="M270.4,408.17 L279.77,445.74 L255.24,422.42 C265.25,422.35 275.25,422.47 285.56,422.78 L261.03,445.52 L270.4,408.17"/>
<path fill="#fff" d="M303.2,155.91 L312.57,193.83 L288.04,169.57 L318.36,171.08 L293.83,192.9 L303.2,155.91"/>
<path fill="#fff" d="M303.2,228.28 L312.57,266.2 L288.04,241.94 L318.36,243.45 L293.83,265.27 L303.2,228.28"/>
<path fill="#fff" d="M303.2,300.65 L312.57,338.57 L288.04,314.31 L318.36,315.82 L293.83,337.64 L303.2,300.65"/>
<path fill="#fff" d="M303.2,373.02 L312.57,410.94 L288.04,386.68 L318.36,388.19 L293.83,410.01 L303.2,373.02"/>
<path fill="#fff" d="M303.2,445.39 L312.57,483.31 L288.04,459.05 L318.36,460.56 L293.83,482.37 L303.2,445.39"/>
<path fill="#fff" d="M336,194.28 L345.37,232.49 L320.84,207.43 L351.16,209.91 L326.63,230.96 L336,194.28"/>
<path fill="#fff" d="M336,266.65 L345.37,304.86 L320.84,279.8 L351.16,282.28 L326.63,303.33 L336,266.65"/>
<path fill="#fff" d="M336,339.02 L345.37,377.23 L320.84,352.17 L351.16,354.65 L326.63,375.69 L336,339.02"/>
<path fill="#fff" d="M336,411.39 L345.37,449.6 L320.84,424.54 L351.16,427.02 L326.63,448.06 L336,411.39"/>
<path fill="#fff" d="M368.8,161.23 L378.17,199.68 L353.64,173.96 L383.96,177.24 L359.43,197.66 L368.8,161.23"/>
<path fill="#fff" d="M368.8,233.6 L378.17,272.05 L353.64,246.33 L383.96,249.61 L359.43,270.02 L368.8,233.6"/>
<path fill="#fff" d="M368.8,305.97 L378.17,344.42 L353.64,318.7 L383.96,321.98 L359.43,342.39 L368.8,305.97"/>
<path fill="#fff" d="M368.8,378.34 L378.17,416.79 L353.64,391.07 L383.96,394.35 L359.43,414.76 L368.8,378.34"/>
<path fill="#fff" d="M368.8,450.71 L378.17,489.16 L353.64,463.44 L383.96,466.72 L359.43,487.13 L368.8,450.71"/>
<path fill="#1A1A1A" opacity="0.2" d="M8,195.25 C178.83,110.03 349.03,140.83 521.26,167.28 C676.47,191.12 833.42,211.85 992,132.75 L992,804.75 C821.17,889.97 650.97,859.17 478.74,832.72 C323.53,808.88 166.58,788.15 8,867.25 L8,195.25 M39.25,214.64 L39.25,819.14 C345.81,690.88 650.43,915.18 960.75,785.36 L960.75,180.86 C654.19,309.12 349.57,84.82 39.25,214.64"/>
</svg>

After

Width:  |  Height:  |  Size: 8.7 KiB

View File

@ -1,31 +1,47 @@
document.addEventListener('DOMContentLoaded', () => {
console.log('DOMContentLoaded event fired');
const checkNicknameButton = document.getElementById('check-nickname');
const registerButton = document.getElementById('register');
const loginButton = document.getElementById('login');
const formBlock = document.getElementById('block-form');
const authForm = document.getElementById('auth-form');
const gameContainer = document.getElementById('game1');
const nicknameInput = document.getElementById('nickname');
const checkNicknameButton = document.getElementById('check-nickname');
const registerForm = document.getElementById('register-form');
const passwordInput = document.getElementById('password');
const confirmPasswordInput = document.getElementById('confirm-password');
const loginPasswordInput = document.getElementById('login-password');
const registerButton = document.getElementById('register');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const formBlock = document.getElementById('block-form');
//const viewSelector = document.getElementById('view-selector');
//const viewPlayersButton = document.getElementById('view-players');
//const viewMatchesButton = document.getElementById('view-matches');
const menuButton = document.querySelector('.burger-menu');
const playerList = document.getElementById('player-list');
const matchList = document.getElementById('match-list');
const dropdownMenu = document.getElementById('dropdown-menu');
const loginPasswordInput = document.getElementById('login-password');
const loginButton = document.getElementById('login');
const authForm2 = document.getElementById('auth-form2');
const nicknameInput2 = document.getElementById('nickname2');
const checkNicknameButton2 = document.getElementById('check-nickname2');
const registerForm2 = document.getElementById('register-form2');
const passwordInput2 = document.getElementById('password2');
const confirmPasswordInput2 = document.getElementById('confirm-password2');
const registerButton2 = document.getElementById('register2');
const loginForm2 = document.getElementById('login-form2');
const loginPasswordInput2 = document.getElementById('login-password2');
const loginButton2 = document.getElementById('login2');
const gameContainer = document.getElementById('game1');
const tournamentContainer = document.getElementById('tournament-bracket');
const pongElements = document.getElementById('pong-elements');
const logo = document.querySelector('.logo');
const postFormButtons = document.getElementById('post-form-buttons');
const localGameButton = document.getElementById('local-game');
const quickMatchButton = document.getElementById('quick-match');
const tournamentButton = document.getElementById('tournament');
let socket;
let token;
let gameState;
let saveData = null;
// Auto-focus and key handling for AUTH-FORM
nicknameInput.focus();
@ -40,15 +56,23 @@ document.addEventListener('DOMContentLoaded', () => {
registerButton.addEventListener('click', handleRegister);
loginButton.addEventListener('click', handleLogin);
checkNicknameButton2.addEventListener('click', handleCheckNickname2);
registerButton2.addEventListener('click', handleRegister2);
loginButton2.addEventListener('click', handleLogin2);
localGameButton.addEventListener('click', startLocalGame);
quickMatchButton.addEventListener('click', startQuickMatch);
tournamentButton.addEventListener('click', startTournament);
async function handleCheckNickname() {
const nickname = nicknameInput.value.trim();
if (nickname) {
window.firstPlayerName = nickname;
try {
const exists = await checkUserExists(nickname);
if (exists) {
authForm.style.display = 'none';
loginForm.style.display = 'block';
// Auto-focus and key handling for LOGIN-FORM
loginPasswordInput.focus();
loginPasswordInput.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
@ -59,7 +83,6 @@ document.addEventListener('DOMContentLoaded', () => {
} else {
authForm.style.display = 'none';
registerForm.style.display = 'block';
// Auto-focus and key handling for REGISTER-FORM
passwordInput.focus();
passwordInput.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
@ -103,11 +126,7 @@ document.addEventListener('DOMContentLoaded', () => {
const result = await registerUser(nickname, password);
if (result) {
registerForm.style.display = 'none';
gameContainer.style.display = 'flex';
formBlock.style.display = 'none';
logo.style.display = 'none';
pongElements.style.display = 'none';
startWebSocketConnection(token);
document.getElementById("post-form-buttons").style.display = 'block';
} else {
alert('Registration failed. Please try again.');
}
@ -141,11 +160,7 @@ document.addEventListener('DOMContentLoaded', () => {
const result = await authenticateUser(nickname, password);
if (result) {
loginForm.style.display = 'none';
gameContainer.style.display = 'flex';
formBlock.style.display = 'none';
logo.style.display = 'none';
pongElements.style.display = 'none';
startWebSocketConnection(token);
document.getElementById("post-form-buttons").style.display = 'block';
} else {
alert('Authentication failed. Please try again.');
}
@ -169,12 +184,196 @@ document.addEventListener('DOMContentLoaded', () => {
return data.authenticated;
}
function startWebSocketConnection(token) {
async function handleCheckNickname2() {
const nickname2 = nicknameInput2.value.trim();
if (nickname2) {
try {
const exists = await checkUserExists2(nickname2);
if (exists) {
authForm2.style.display = 'none';
loginForm2.style.display = 'block';
loginPasswordInput2.focus();
loginPasswordInput2.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
loginButton2.click();
}
});
} else {
authForm2.style.display = 'none';
registerForm2.style.display = 'block';
passwordInput2.focus();
passwordInput2.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
confirmPasswordInput2.focus();
confirmPasswordInput2.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
registerButton2.click();
}
});
}
});
}
} catch (error) {
console.error('Error checking user existence:', error);
}
} else {
alert('Please enter a nickname.');
}
}
async function checkUserExists2(username) {
const response = await fetch('/check_user_exists/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username })
});
const data = await response.json();
return data.exists;
}
async function handleRegister2() {
const nickname2 = nicknameInput2.value.trim();
const password2 = passwordInput2.value.trim();
const confirmPassword2 = confirmPasswordInput2.value.trim();
if (password2 === confirmPassword2) {
try {
const result = await registerUser2(nickname2, password2);
if (result) {
registerForm2.style.display = 'none';
startLocalGame2();
} else {
alert('Registration failed. Please try again.');
}
} catch (error) {
console.error('Error registering user:', error);
}
} else {
alert('Passwords do not match.');
}
}
async function registerUser2(username, password) {
const response = await fetch('/register_user/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.registered) {
token2 = data.token;
}
return data.registered;
}
async function handleLogin2() {
const nickname2 = nicknameInput2.value.trim();
const password2 = loginPasswordInput2.value.trim();
try {
const result = await authenticateUser2(nickname2, password2);
if (result) {
loginForm2.style.display = 'none';
startLocalGame2();
} else {
alert('Authentication failed. Please try again.');
}
} catch (error) {
console.error('Error authenticating user:', error);
}
}
async function authenticateUser2(username, password) {
const response = await fetch('/authenticate_user/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.authenticated) {
token2 = data.token;
}
return data.authenticated;
}
function startLocalGame() {
console.log("starting a Local Game..");
document.getElementById("post-form-buttons").style.display = 'none';
authForm2.style.display = 'block';
nicknameInput2.focus();
nicknameInput2.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
event.preventDefault();
checkNicknameButton2.click();
}
});
}
function startLocalGame2() {
nickname = nicknameInput.value.trim();
nickname2 = nicknameInput2.value.trim();
saveData = {
type: 'local',
player1_name: nickname,
player2_name: nickname2
};
gameContainer.style.display = 'flex';
logo.style.display = 'none';
pongElements.style.display = 'none';
formBlock.style.display = 'none';
startWebSocketConnection(token, 2);
}
function startQuickMatch() {
saveData = {
type: 'quick'
}
gameContainer.style.display = 'flex';
logo.style.display = 'none';
pongElements.style.display = 'none';
formBlock.style.display = 'none';
document.getElementById('player1-name').textContent = "player 1";
document.getElementById('player2-name').textContent = "player 2";
document.getElementById('game-text').textContent = "";
document.getElementById('player1-score').textContent = 0;
document.getElementById('player2-score').textContent = 0;
startWebSocketConnection(token, 1);
}
function startTournament() {
saveData = {
type: 'tournoi'
}
tournamentContainer.style.display = 'flex';
logo.style.display = 'none';
pongElements.style.display = 'none';
formBlock.style.display = 'none';
startWebSocketConnection(token, 42);
}
function startWebSocketConnection(token, players) {
socket = new WebSocket(`ws://${window.location.host}/ws/game/`);
socket.onopen = function (event) {
console.log('WebSocket connection established');
socket.send(JSON.stringify({ type: 'authenticate', token: token }));
if (players === 1) {
console.log("Sending token for a quick match game");
socket.send(JSON.stringify({ type: 'authenticate', token: token }));
} else if (players === 2) {
console.log("Sending tokens for a local game");
socket.send(JSON.stringify({ type: 'authenticate2', token_1: token, token_2: token2 }));
} else {
console.log("Sending token for a tournament game")
socket.send(JSON.stringify({ type: 'authenticate3', token: token }));
}
};
socket.onmessage = function (event) {
@ -185,15 +384,36 @@ document.addEventListener('DOMContentLoaded', () => {
console.log('Entered the WAITING ROOM');
} else if (data.type === 'game_start') {
console.log('Game started:', data.game_id, '(', data.player1, 'vs', data.player2, ')');
startGame(data.game_id, data.player1, data.player2);
gameContainer.style.display = 'flex';
document.addEventListener('keydown', handleKeyDown);
} else if (data.type === 'game_state_update') {
updateGameState(data.game_state);
} else if (data.type === 'player_disconnected') {
console.log("Player disconnected:", data.player);
console.log('Player disconnected:', data.player);
} else if (data.type === 'game_ended') {
console.log("Game ended:", data.game_id);
console.log('Game ended:', data.game_id);
} else if (data.type === 'error') {
console.error(data.message);
} else if (data.type === 'update_tournament_waiting_room') {
// Update the HTML content of the tournament bracket
document.getElementById('tournament-bracket').innerHTML = data.html;
// Reattach the event listener to the "Start Tournament" button
const startButton = document.getElementById('start-tournament-btn');
if (startButton) {
startButton.addEventListener('click', function() {
if (typeof socket !== 'undefined' && socket.readyState === WebSocket.OPEN) {
console.log('Start TOURNAMENT sent..');
socket.send(JSON.stringify({type: 'start_tournament'}));
} else {
console.error('WebSocket is not open or undefined');
}
});
}
} else if (data.type === 'update_brackets') {
// Update the HTML content of the tournament bracket
document.getElementById('tournament-bracket').innerHTML = data.html;
} else if (data.type === 'tournament_end') {
console.log('Tournament ended, the winner is:', data.winner);
} else {
console.log('Message from server:', data.type, data.message);
}
@ -208,24 +428,14 @@ document.addEventListener('DOMContentLoaded', () => {
};
}
function startGame(gameCode, player1_name, player2_name) {
document.getElementById('gameCode').textContent = `Game Code: ${gameCode}`;
document.getElementById('player1-name').textContent = `${player1_name}`;
document.getElementById('player2-name').textContent = `${player2_name}`;
document.addEventListener('keydown', handleKeyDown);
}
function handleKeyDown(event) {
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
console.log('Key press: ', event.key);
if (event.key === 'ArrowUp' || event.key === 'ArrowDown' || event.key === 'w' || event.key === 's') {
sendKeyPress(event.key.toLowerCase());
}
}
function sendKeyPress(key) {
if (socket.readyState === WebSocket.OPEN) {
console.log('Key sent: ', key);
socket.send(JSON.stringify({ type: 'key_press', key }));
}
}
@ -233,165 +443,76 @@ document.addEventListener('DOMContentLoaded', () => {
function updateGameState(newState) {
gameState = newState;
renderGame();
checkForWinner();
}
function renderGame() {
const player1Pad = document.getElementById('player1-pad');
player1Pad.style.top = `${gameState.player1_position}px`;
document.getElementById('player1-name').textContent = `${gameState.player1_name}`;
document.getElementById('player2-name').textContent = `${gameState.player2_name}`;
const player2Pad = document.getElementById('player2-pad');
player2Pad.style.top = `${gameState.player2_position}px`;
document.getElementById('player1-pad').style.top = `${gameState.player1_position}px`;
document.getElementById('player2-pad').style.top = `${gameState.player2_position}px`;
const ball = document.getElementById('ball');
ball.style.left = `${gameState.ball_position.x}px`;
ball.style.top = `${gameState.ball_position.y}px`;
document.getElementById('ball').style.left = `${gameState.ball_position.x}px`;
document.getElementById('ball').style.top = `${gameState.ball_position.y}px`;
const player1Score = document.getElementById('player1-score');
player1Score.textContent = gameState.player1_score;
document.getElementById('player1-score').textContent = gameState.player1_score;
document.getElementById('player2-score').textContent = gameState.player2_score;
const player2Score = document.getElementById('player2-score');
player2Score.textContent = gameState.player2_score;
document.getElementById('game-text').textContent = gameState.game_text;
}
// viewSelector.addEventListener('change', function() {
// const selectedView = this.value;
// Masquer les deux listes par défaut
// playerList.style.display = 'none';
// matchList.style.display = 'none';
// Afficher la liste sélectionnée
// if (selectedView === 'player-list') {
// playerList.style.display = 'block';
// fetchPlayers();
//} else if (selectedView === 'match-list') {
// matchList.style.display = 'block';
// fetchMatches();
//}
//})
console.log('Here');
function toggleMenu() {
console.log('Menu toggled');
if (dropdownMenu.style.display === "block") {
dropdownMenu.style.display = "none";
} else {
dropdownMenu.style.display = "block";
}
const starsContainer = document.getElementById('stars');
for (let i = 0; i < 500; i++) {
const star = document.createElement('div');
star.className = 'star';
star.style.width = `${Math.random() * 3}px`;
star.style.height = star.style.width;
star.style.left = `${Math.random() * 100}%`;
star.style.top = `${Math.random() * 100}%`;
star.style.animationDuration = `${Math.random() * 2 + 1}s`;
starsContainer.appendChild(star);
}
function showTable(tableId) {
// Masquer tous les tableaux
if (playerList) {
playerList.style.display = 'none';
}
if (matchList) {
matchList.style.display = 'none';
}
const homeButton = document.getElementById('home');
const replayButton = document.getElementById('retry');
const gameControls = document.getElementById('game-controls');
// Afficher le tableau sélectionné
if (tableId === 'player-list') {
if (playerList) {
playerList.style.display = 'block';
}
fetchPlayers();
} else if (tableId === 'match-list') {
if (matchList) {
matchList.style.display = 'block';
}
fetchMatches();
}
homeButton.addEventListener('click', () => {
gameContainer.style.display = 'none';
gameControls.style.display = 'none';
// Masquer le menu après la sélection
if (dropdownMenu) {
dropdownMenu.style.display = 'none';
}
}
logo.style.display = 'block'
// Ajouter les gestionnaires d'événements
if (menuButton) {
menuButton.addEventListener('click', toggleMenu);
}
formBlock.style.display = 'block';
postFormButtons.style.display = 'flex';
const links = document.querySelectorAll('#dropdown-menu a');
links.forEach(link => {
link.addEventListener('click', (event) => {
event.preventDefault(); // Empêche le comportement par défaut du lien
const tableId = link.getAttribute('data-table');
showTable(tableId);
});
setupFirstPlayer();
});
function fetchMatches() {
fetch('/api/match_list/')
.then(response => response.json())
.then(data => {
if (data.matches) {
displayMatches(data.matches);
function setupFirstPlayer() {
const firstPlayerName = window.firstPlayerName;
document.getElementById('player1-name').textContent = firstPlayerName;
}
replayButton.addEventListener('click', () => {
document.getElementById('player1-name').textContent = saveData.player1_name;
document.getElementById('player2-name').textContent = saveData.player2_name;
startLocalGame2();
});
function checkForWinner() {
if (gameState.player1_score === 3 || gameState.player2_score === 3) {
if (saveData.type != "tournoi"){
gameControls.style.display = 'flex';
homeButton.style.display = 'block';
replayButton.style.display = 'none';
console.log(saveData.type);
if (saveData.type === 'local'){
replayButton.style.display = 'block';
}
})
.catch(error => console.error('Error fetching match data:', error));
}
function fetchPlayers(){
fetch('/api/player_list/')
.then(response => response.json())
.then(data => {
if (data.players) {
displayPlayers(data.players);
}
})
.catch(error => console.error('Error fetching match data:', error));
}
function displayMatches(matches) {
const matchListBody = document.querySelector('#match-list tbody');
matchListBody.innerHTML = '';
matches.forEach(match => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${match.id}</td>
<td>${match.player1__name}</td>
<td>${match.player2__name}</td>
<td>${match.score_player1}</td>
<td>${match.score_player2}</td>
<td>${match.winner__name}</td>
<td>${match.nbr_ball_touch_p1}</td>
<td>${match.nbr_ball_touch_p2}</td>
<td>${match.duration}</td>
<td>${match.date}</td>
<td>${match.is_tournoi}</td>
<td>${match.tournoi__name}</td>
`;
matchListBody.appendChild(row);
});
}
function displayPlayers(players) {
const playersListBody = document.querySelector('#player-list tbody');
playersListBody.innerHTML = '';
players.forEach(player => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${player.id}</td>
<td>${player.name}</td>
<td>${player.total_match}</td>
<td>${player.total_win}</td>
<td>${player.p_win}</td>
<td>${player.m_score_match}</td>
<td>${player.m_score_adv_match}</td>
<td>${player.best_score}</td>
<td>${player.m_nbr_ball_touch}</td>
<td>${player.total_duration}</td>
<td>${player.m_duration}</td>
<td>${player.num_participated_tournaments}</td>
<td>${player.num_won_tournaments}</td>
`;
playersListBody.appendChild(row);
});
}
}
}
});

View File

@ -1,18 +1,24 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<html lang="fr">
<head>
<meta charset="UTF-8">
<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' %}">
<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>
</head>
<body>
<div class="language-switcher">
<img id="lang-fr" src="{% static 'flags/fr.svg' %}" alt="Français">
<img id="lang-en" src="{% static 'flags/us.svg' %}" alt="English">
<img id="lang-it" src="{% static 'flags/it.svg' %}" alt="Italiano">
<img id="lang-es" src="{% static 'flags/es.svg' %}" alt="Español">
<img id="lang-de" src="{% static 'flags/de.svg' %}" alt="Deutsch">
</div>
<div class="background">
<div class="stars" id="stars"></div>
</div>
@ -22,26 +28,67 @@
<div class="ball_anim"></div>
</div>
<button id="settings-btn">⚙️ Réglages</button>
<div id="settings-menu" style="display: none;">
<button id="close-settings">✖️</button>
<h2>Reglages</h2>
<label for="color-picker">Couleur:</label>
<input type="color" id="color-picker">
<br>
<label for="font-selector">Police:</label>
<select id="font-selector">
<option value="Arial">Arial</option>
<option value="Verdana">Verdana</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Courier New">Courier New</option>
</select>
<br>
<label for="font-size-slider">Taille:</label>
<input type="range" id="font-size-slider" min="12" max="36" value="16">
</div>
<div class="container" id="block-form">
<h1>BIENVENUE DANS LE PONG 42</h1>
<h1 id="welcome">BIENVENUE DANS LE PONG 42</h1>
<div class="input-container">
<div id="auth-form">
<label for="nickname">Enter your nickname:</label>
<label for="nickname" id="label-nickname">Enter your nickname:</label>
<input type="text" id="nickname" name="nickname">
<button id="check-nickname">Check Nickname</button>
</div>
<div id="register-form" style="display: none;">
<label for="password">Enter your password:</label>
<label for="password" id="label-password">Enter your password:</label>
<input type="password" id="password" name="password">
<label for="confirm-password">Confirm your password:</label>
<label for="confirm-password" id="label-confirm-password">Confirm your password:</label>
<input type="password" id="confirm-password" name="confirm-password">
<button id="register">Register</button>
</div>
<div id="login-form" style="display: none;">
<label for="login-password">Enter your password:</label>
<label for="login-password" id="label-login-password">Enter your password:</label>
<input type="password" id="login-password" name="login-password">
<button id="login">Login</button>
</div>
<div id="post-form-buttons" style="display: none;">
<button id="local-game">Local Game</button>
<button id="quick-match">Quick Match</button>
<button id="tournament">Tournament</button>
</div>
<div id="auth-form2" style="display: none;">
<label for="nickname" id="label-nickname2">Enter the second player's nickname:</label>
<input type="text" id="nickname2" name="nickname">
<button id="check-nickname2">Check Nickname</button>
</div>
<div id="register-form2" style="display: none;">
<label for="password" id="label-password2">Enter the second player's password:</label>
<input type="password" id="password2" name="password">
<label for="confirm-password" id="label-confirm-password2">Confirm the second player's password:</label>
<input type="password" id="confirm-password2" name="confirm-password">
<button id="register2">Register</button>
</div>
<div id="login-form2" style="display: none;">
<label for="login-password" id="label-login-password2">Enter the second player's password:</label>
<input type="password" id="login-password2" name="login-password">
<button id="login2">Login</button>
</div>
</div>
</div>
@ -50,24 +97,35 @@
<div id="dropdown-menu" class="dropdown-content">
<a href="#" data-table="player-list">Players</a>
<a href="#" data-table="match-list">Matches</a>
<a href="#" data-table="tournoi-list">Tournois</a>
<a href="#" data-table="blockchain-list">blockchain</a>
</div>
</div>
<div id="tournament-bracket" style="display: none;"></div>
<div id="game-controls" style="display: none;">
<button id="home">Home</button>
<button id="retry">Rejouer</button>
</div>
<div id="game1" style="display: none;">
<div id="gameCode" class="game-code">Game Code : </div>
<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>
<div id="player1-pad" class="pad"></div>
<div id="player2-pad" class="pad"></div>
<div id="ball"></div>
<div id="game-text" class="gameText"></div>
</div>
</div>
<div id="match-list" class="content-list" style="display: none;">
<h1>Matches</h1>
<input type="text" id="search-match-player" placeholder="Rechercher par nom de joueur">
<input type="date" id="search-match-date">
<table>
<thead>
<tr>
@ -86,32 +144,15 @@
</tr>
</thead>
<tbody>
{% for match in matches %}
<tr>
<td>{{ match.id }}</td>
<td>{{ match.player1.name }}</td>
<td>{{ match.player2.name }}</td>
<td>{{ match.score_player1 }}</td>
<td>{{ match.score_player2 }}</td>
<td>{{ match.winner.name }}</td>
<td>{{ match.nbr_ball_touch_p1 }}</td>
<td>{{ match.nbr_ball_touch_p2 }}</td>
<td>{{ match.duration }}</td>
<td>{{ match.date }}</td>
<td>{{ match.is_tournoi }}</td>
<td>{{ match.tournoi.name }}</td>
</tr>
{% empty %}
<tr>
<td colspan="12">No matches found.</td>
</tr>
{% endfor %}
</tbody>
</tbody>
</table>
<button id="generate-match-chart">Générer le graphique</button>
<canvas id="match-chart" style="display:none;"></canvas>
</div>
<div id="player-list" class="content-list" style="display:none;">
<div id="player-list" class="content-list" style="display: none;">
<h1>Players</h1>
<input type="text" id="search-player" placeholder="Rechercher par nom">
<table>
<thead>
<tr>
@ -131,45 +172,36 @@
</tr>
</thead>
<tbody>
{% for player in players %}
</tbody>
</table>
<button id="generate-player-chart">Générer le graphique</button>
<canvas id="player-chart" style="display:none;"></canvas>
</div>
<div id="tournoi-list" class="content-list" style="display: none;">
<h1>Tournois</h1>
<table>
<thead>
<tr>
<td>{{ player.id }}</td>
<td>{{ player.name }}</td>
<td>{{ player.total_match }}</td>
<td>{{ player.total_win }}</td>
<td>{{ player.p_win }}</td>
<td>{{ player.m_score_match }}</td>
<td>{{ player.m_score_adv_match }}</td>
<td>{{ player.best_score }}</td>
<td>{{ player.m_nbr_ball_touch }}</td>
<td>{{ player.total_duration }}</td>
<td>{{ player.m_duration }}</td>
<td>{{ player.num_participated_tournaments }}</td>
<td>{{ player.num_won_tournaments }}</td>
<th>ID</th>
<th>Name</th>
<th>Nbr_players</th>
<th>Date</th>
<th>Winner</th>
</tr>
{% empty %}
<tr>
<td colspan="13">No players found.</td>
</tr>
{% endfor %}
</tbody>
</thead>
<tbody>
</tbody>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0/dist/chartjs-adapter-moment.min.js"></script>
<script src="{% static 'game.js' %}"></script>
<script>
const starsContainer = document.getElementById('stars');
for (let i = 0; i < 500; i++) {
const star = document.createElement('div');
star.className = 'star';
star.style.width = `${Math.random() * 3}px`;
star.style.height = star.style.width;
star.style.left = `${Math.random() * 100}%`;
star.style.top = `${Math.random() * 100}%`;
star.style.animationDuration = `${Math.random() * 2 + 1}s`;
starsContainer.appendChild(star);
}
</script>
<script src="{% static 'burger.js' %}"></script>
<script src="{% static 'language.js' %}"></script>
</body>
</html>

113
pong/static/language.js Normal file
View File

@ -0,0 +1,113 @@
document.addEventListener('DOMContentLoaded', () => {
const translations = {
fr: {
welcome: "BIENVENUE DANS LE PONG 42",
labelNickname: "Entrez votre surnom:",
labelPassword: "Entrez votre mot de passe:",
labelConfirmPassword: "Confirmez votre mot de passe:",
labelLoginPassword: "Entrez votre mot de passe:"
},
en: {
welcome: "WELCOME TO PONG 42",
labelNickname: "Enter your nickname:",
labelPassword: "Enter your password:",
labelConfirmPassword: "Confirm your password:",
labelLoginPassword: "Enter your password:"
},
it: {
welcome: "BENVENUTO A PONG 42",
labelNickname: "Inserisci il tuo soprannome:",
labelPassword: "Inserisci la tua password:",
labelConfirmPassword: "Conferma la tua password:",
labelLoginPassword: "Inserisci la tua password:"
},
es: {
welcome: "BIENVENIDO A PONG 42",
labelNickname: "Introduce tu apodo:",
labelPassword: "Introduce tu contraseña:",
labelConfirmPassword: "Confirma tu contraseña:",
labelLoginPassword: "Introduce tu contraseña:"
},
de: {
welcome: "WILLKOMMEN BEI PONG 42",
labelNickname: "Geben Sie Ihren Spitznamen ein:",
labelPassword: "Geben Sie Ihr Passwort ein:",
labelConfirmPassword: "Bestätigen Sie Ihr Passwort:",
labelLoginPassword: "Geben Sie Ihr Passwort ein:"
}
};
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
const expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}
function getCookie(name) {
const cname = name + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(cname) === 0) {
return c.substring(cname.length, c.length);
}
}
return "";
}
function changeLanguage(lang) {
setCookie('preferredLanguage', lang, 365);
document.getElementById('welcome').innerText = translations[lang].welcome;
document.getElementById('label-nickname').innerText = translations[lang].labelNickname;
document.getElementById('label-password').innerText = translations[lang].labelPassword;
document.getElementById('label-confirm-password').innerText = translations[lang].labelConfirmPassword;
document.getElementById('label-login-password').innerText = translations[lang].labelLoginPassword;
}
function setLanguageFromCookie() {
const preferredLanguage = getCookie('preferredLanguage');
if (preferredLanguage && translations[preferredLanguage]) {
changeLanguage(preferredLanguage);
} else {
changeLanguage('fr'); // Default to French if no cookie is found
}
}
document.getElementById('lang-fr').addEventListener('click', () => changeLanguage('fr'));
document.getElementById('lang-en').addEventListener('click', () => changeLanguage('en'));
document.getElementById('lang-it').addEventListener('click', () => changeLanguage('it'));
document.getElementById('lang-es').addEventListener('click', () => changeLanguage('es'));
document.getElementById('lang-de').addEventListener('click', () => changeLanguage('de'));
window.onload = setLanguageFromCookie;
document.getElementById('settings-btn').addEventListener('click', function() {
document.getElementById('settings-menu').style.display = 'block';
});
document.getElementById('close-settings').addEventListener('click', function() {
document.getElementById('settings-menu').style.display = 'none';
});
document.getElementById('color-picker').addEventListener('input', function() {
document.body.style.color = this.value;
document.querySelectorAll('button').forEach(function(button) {
button.style.backgroundColor = this.value;
}, this);
});
document.getElementById('font-selector').addEventListener('change', function() {
document.body.style.fontFamily = this.value;
});
document.getElementById('font-size-slider').addEventListener('input', function() {
document.body.style.fontSize = this.value + 'px';
});
});

View File

@ -1,5 +1,4 @@
/* General styles */
body,
html {
font-family: Arial, sans-serif;
@ -12,10 +11,10 @@ html {
align-items: center;
justify-content: center;
height: 100%;
overflow: hidden;
overflow: auto;
}
label {
margin: 10px 0 5px;
}
@ -59,20 +58,10 @@ button:hover {
align-items: center;
}
.game-code {
font-size: 24px;
position: absolute;
top: 10px;
}
#gameCode {
left: 10px;
}
.name {
font-size: 24px;
position: absolute;
top: 30px;
top: 20px;
}
#player1-name {
@ -144,6 +133,13 @@ button:hover {
position: absolute;
}
#game-text {
font-size: 64px;
color: #00ffff;
position: absolute;
top: 150px;
}
.logo {
position: absolute;
top: 20px;
@ -259,12 +255,14 @@ button:hover {
position: relative;
z-index: 10;
max-width: 80%;
overflow: auto;
}
.navbar {
position: absolute;
top: 0;
right: 0;
top: 30px;
right: 10px;
padding: 10px;
}
@ -272,28 +270,203 @@ button:hover {
font-size: 24px;
background: none;
border: none;
color: white;
color: #00ffff;
cursor: pointer;
transition: color 0.3s ease;
}
.burger-menu:hover {
color: #ffffff;
}
.dropdown-content {
display: none;
position: absolute;
top: 100%;
right: 0;
background-color: #f9f9f9;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
margin-top: 10px;
background-color: #1a1a2e;
color: #ffffff;
box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.3);
border-radius: 5px;
z-index: 1;
width: max-content;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
.dropdown-content.show {
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
.dropdown-content a {
color: #ffffff;
padding: 12px 16px;
text-decoration: none;
display: block;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
transition: background-color 0.3s ease;
}
.show {display: block;}
.dropdown-content a:hover {
background-color: #333;
color: #00ffff;
}
.language-switcher {
position: absolute;
top: 10px;
right: 10px;
display: flex;
gap: 10px;
}
.language-switcher img {
width: 30px;
height: 20px;
cursor: pointer;
}
#settings-btn {
position: fixed;
bottom: 10px;
right: 10px;
cursor: pointer;
z-index: 1000;
border: none;
border-radius: 50%;
padding: 10px;
font-size: 18px;
}
#settings-menu {
position: fixed;
bottom: 50px;
right: 10px;
padding: 20px;
background-color: rgb(66, 63, 63);
border: 1px solid #ccc;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 250px;
z-index: 1000;
}
#close-settings {
position: absolute;
top: 10px;
right: 10px;
background: none;
border: none;
cursor: pointer;
font-size: 16px;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
padding-top: 60px;
}
.modal-content {
background-color: #fefefe;
margin: 5% auto;
padding: 20px;
border: 5px solid #888;
width: 80%;
max-height: 70vh;
overflow-y: auto;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
}
/*
.tournament-waiting-room {
background-color: rgba(0, 0, 0, 0.6);
padding: 20px;
border-radius: 15px;
color: #00ffff;
width: 50%;
margin: auto;
text-align: center;
box-shadow: 0 0 30px #00ffff, inset 0 0 20px #00ffff;
}
.tournament-waiting-room h2 {
font-family: 'Arial', sans-serif;
font-size: 2em;
margin-bottom: 15px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.7);
}
.tournament-waiting-room p {
font-family: 'Verdana', sans-serif;
font-size: 1.2em;
margin-bottom: 20px;
text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.6);
}
.tournament-waiting-room ul {
list-style-type: none;
padding: 0;
}
*/
body {
color: rgb(0, 255, 255); /* Valeur par défaut */
font-family: Arial, sans-serif;
font-size: 16px;
}
canvas {
max-width: 100%;
height: auto;
margin-top: 20px;
}
#game-controls {
display: flex;
justify-content: center;
gap: 20px;
margin-bottom: 10px;
}
#game-controls button {
background-color: #00ffff;
color: #000033;
border: none;
padding: 1rem 2rem;
font-size: 1rem;
cursor: pointer;
transition: all 0.3s ease;
border-radius: 10px;
text-transform: uppercase;
letter-spacing: 2px;
}
#game-controls button:hover {
background-color: #000033;
color: #00ffff;
box-shadow: 0 0 20px #00ffff;
}

View File

@ -1,6 +1,8 @@
Django
django
psycopg2
python-dotenv
channels
daphne
djangorestframework
web3
python-json-logger==2.0.7