mirror of
https://github.com/AudebertAdrien/ft_transcendence.git
synced 2025-12-16 05:57:48 +01:00
up
This commit is contained in:
commit
034e0a85a8
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,3 +1,4 @@
|
||||
venv/
|
||||
__pycache__/
|
||||
.env
|
||||
certs
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
FROM python:latest
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE 1
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
|
||||
@ -10,9 +9,10 @@ RUN apt update && apt upgrade -y
|
||||
|
||||
COPY requirements.txt .
|
||||
COPY manage.py .
|
||||
COPY certs/ certs/
|
||||
|
||||
RUN python3 -m venv venv
|
||||
RUN venv/bin/pip3 install --upgrade pip
|
||||
RUN venv/bin/pip3 install --no-cache-dir -r requirements.txt
|
||||
RUN venv/bin/pip3 install --no-cache-dir -r requirements.txt -v
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
29
config/nginx.conf
Normal file
29
config/nginx.conf
Normal file
@ -0,0 +1,29 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
# Redirect HTTP to HTTPS
|
||||
location / {
|
||||
return 301 https://localhost:1443$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
server_name localhost;
|
||||
|
||||
ssl_certificate /etc/nginx/ssl/certificate.crt;
|
||||
ssl_certificate_key /etc/nginx/ssl/private.key;
|
||||
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers on;
|
||||
|
||||
# Proxy normal HTTP requests to Django
|
||||
location / {
|
||||
proxy_pass http://backend:8080/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
28
config/ssl.conf
Normal file
28
config/ssl.conf
Normal file
@ -0,0 +1,28 @@
|
||||
[req]
|
||||
distinguished_name = req_distinguished_name
|
||||
req_extensions = req_ext
|
||||
x509_extensions = req_ext
|
||||
|
||||
[req_distinguished_name]
|
||||
countryName = FR
|
||||
countryName_default = FR
|
||||
stateOrProvinceName = Pyrénées Orientales
|
||||
stateOrProvinceName_default = Pyrénées Orientales
|
||||
localityName = Perpignan
|
||||
localityName_default = Perpignan
|
||||
organizationName = 42Perpignan
|
||||
organizationName_default = 42Perpignan
|
||||
commonName = www.ft_transcendence.com
|
||||
commonName_default = localhost
|
||||
|
||||
[req_ext]
|
||||
subjectAltName = @alt_names
|
||||
basicConstraints = CA:FALSE
|
||||
keyUsage = digitalSignature, keyEncipherment
|
||||
extendedKeyUsage = serverAuth
|
||||
|
||||
[alt_names]
|
||||
DNS.1 = localhost
|
||||
DNS.2 = www.ft_transcendence.com
|
||||
DNS.3 = ft_transcendence.com
|
||||
IP.1 = 127.0.0.1
|
||||
182
docker-compose-elk.yml
Normal file
182
docker-compose-elk.yml
Normal file
@ -0,0 +1,182 @@
|
||||
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
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
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
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
|
||||
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
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
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
|
||||
networks:
|
||||
- app-network
|
||||
|
||||
volumes:
|
||||
pong_django_logs:
|
||||
pong_es_data_01:
|
||||
driver: local
|
||||
pong_kibana:
|
||||
driver: local
|
||||
pong_logstash_data01:
|
||||
driver: local
|
||||
certs:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
app-network:
|
||||
name: app-network
|
||||
external: true
|
||||
@ -1,62 +1,17 @@
|
||||
services:
|
||||
setup:
|
||||
image: docker.elastic.co/elasticsearch/elasticsearch:${STACK_VERSION}
|
||||
container_name: setup
|
||||
user: "0"
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
ports:
|
||||
- "1080:80"
|
||||
- "1443:443"
|
||||
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
|
||||
- ./config/nginx.conf:/etc/nginx/conf.d/default.conf
|
||||
- ./certs/ssl:/etc/nginx/ssl
|
||||
networks:
|
||||
- app-network
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
backend:
|
||||
build:
|
||||
@ -115,105 +70,7 @@ services:
|
||||
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
|
||||
@ -225,14 +82,7 @@ volumes:
|
||||
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:
|
||||
|
||||
@ -30,7 +30,7 @@ KIBANA_PASSWORD=
|
||||
ENCRYPTION_KEY=c34d38b3a14956121ff2170e5030b471551370178f43e5626eec58b04a30fae2
|
||||
|
||||
# Web3 settings
|
||||
PRIVATE_KEY=aaaa
|
||||
WEB3_PROVIDER=bbbb
|
||||
CONTRACT_ADDRESS=0x11111111
|
||||
WEB3_ACCOUNT=0x00000000
|
||||
PRIVATE_KEY=
|
||||
WEB3_PROVIDER=
|
||||
CONTRACT_ADDRESS=
|
||||
WEB3_ACCOUNT=
|
||||
|
||||
44
makefile
44
makefile
@ -1,26 +1,44 @@
|
||||
MAIN_PROJECT_NAME=main_project
|
||||
ELK_PROJECT_NAME=elk_project
|
||||
|
||||
COMPOSE_FILE=docker-compose.yml
|
||||
COMPOSE=docker compose -f $(COMPOSE_FILE)
|
||||
ELK_COMPOSE_FILE=docker-compose-elk.yml
|
||||
|
||||
COMPOSE=docker compose -f $(COMPOSE_FILE) -p $(MAIN_PROJECT_NAME)
|
||||
ELK_COMPOSE=docker compose -f $(ELK_COMPOSE_FILE) -p $(ELK_PROJECT_NAME)
|
||||
|
||||
CONTAINER=$(c)
|
||||
|
||||
up: down
|
||||
$(COMPOSE) build
|
||||
$(COMPOSE) build
|
||||
$(COMPOSE) up -d $(CONTAINER) || true
|
||||
|
||||
build:
|
||||
$(COMPOSE) build $(CONTAINER)
|
||||
|
||||
start:
|
||||
$(COMPOSE) start $(CONTAINER)
|
||||
|
||||
stop:
|
||||
$(COMPOSE) stop $(CONTAINER)
|
||||
|
||||
down:
|
||||
$(COMPOSE) down $(CONTAINER)
|
||||
|
||||
destroy:
|
||||
$(COMPOSE) down -v --rmi all
|
||||
|
||||
ssl-certs:
|
||||
mkdir -p certs/ssl
|
||||
openssl req -x509 -nodes -days 365 -newkey rsa:4096 \
|
||||
-keyout certs/ssl/private.key -out certs/ssl/certificate.crt \
|
||||
-config config/ssl.conf
|
||||
|
||||
# Manage ELK stack
|
||||
|
||||
elk-up:
|
||||
$(ELK_COMPOSE) up -d --remove-orphans || true
|
||||
|
||||
elk-down:
|
||||
$(ELK_COMPOSE) down --remove-orphans
|
||||
|
||||
elk-destroy:
|
||||
$(ELK_COMPOSE) down --remove-orphans -v --rmi all
|
||||
|
||||
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
|
||||
@ -28,17 +46,9 @@ kill-pid:
|
||||
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)
|
||||
|
||||
ps:
|
||||
$(COMPOSE) ps
|
||||
|
||||
db-shell:
|
||||
$(COMPOSE) exec db psql -U 42student players_db
|
||||
|
||||
re: destroy up
|
||||
|
||||
help:
|
||||
@echo "Usage:"
|
||||
@echo " make build [c=service] # Build images"
|
||||
@ -48,7 +58,7 @@ help:
|
||||
@echo " make destroy # Stop and remove containers and volumes"
|
||||
@echo " make stop [c=service] # Stop containers"
|
||||
@echo " make logs [c=service] # Tail logs of containers"
|
||||
@echo " make ps # List containers"
|
||||
@echo " make ssl-certs # create ssl certificate"
|
||||
@echo " make help # Show this help"
|
||||
|
||||
.PHONY: up build start stop down destroy logs ps db-shell help
|
||||
|
||||
@ -9,6 +9,7 @@ from asgiref.sync import sync_to_async
|
||||
from .models import Tournoi
|
||||
|
||||
class Game:
|
||||
|
||||
def __init__(self, game_id, player1, player2, localgame):
|
||||
self.game_id = game_id
|
||||
self.player1 = player1
|
||||
@ -43,12 +44,14 @@ class Game:
|
||||
}
|
||||
self.speed = 1
|
||||
self.game_loop_task = None
|
||||
self.database = None
|
||||
self.ended = False
|
||||
self.p1_mov = 0
|
||||
self.p2_mov = 0
|
||||
self.bt1 = 0
|
||||
self.bt2 = 0
|
||||
self.start_time = datetime.now()
|
||||
self.future_ball_position = {'x': 390, 'y': 190}
|
||||
|
||||
async def start_game(self):
|
||||
print(f"- Game #{self.game_id} STARTED ({self.game_state['player1_name']} vs {self.game_state['player2_name']}) --- ({self})")
|
||||
@ -57,41 +60,42 @@ class Game:
|
||||
|
||||
async def game_loop(self):
|
||||
print(" In the game loop..")
|
||||
x = 0
|
||||
x = 59
|
||||
while not self.ended:
|
||||
if self.botgame:
|
||||
x += 1
|
||||
if x == 60:
|
||||
await self.update_bot_position()
|
||||
# Random BOT difficulty..
|
||||
steps = 60#random.randint(10, 60)
|
||||
self.future_ball_position = await self.predict_ball_trajectory(steps)
|
||||
x = 0
|
||||
if self.botgame:
|
||||
await self.update_bot_position()
|
||||
await self.handle_pad_movement()
|
||||
await self.update_game_state()
|
||||
await self.send_game_state()
|
||||
await asyncio.sleep(1/60) # Around 60 FPS
|
||||
|
||||
async def update_bot_position(self):
|
||||
future_ball_position = self.predict_ball_trajectory()
|
||||
|
||||
target_y = future_ball_position['y']
|
||||
#future_ball_position = self.predict_ball_trajectory()
|
||||
target_y = self.future_ball_position['y']
|
||||
player2_position = self.game_state['player2_position']
|
||||
|
||||
# Adjusts bot position based on expected ball position
|
||||
if player2_position < target_y < player2_position + 80:
|
||||
pass #bot already placed
|
||||
elif player2_position < target_y:
|
||||
#self.p2_mov = 1
|
||||
self.game_state['player2_position'] = min(player2_position + (50 * self.speed), 300)
|
||||
self.p2_mov = 1
|
||||
#self.game_state['player2_position'] = min(player2_position + (50 * self.speed), 300)
|
||||
elif player2_position + 80 > target_y:
|
||||
#self.p2_mov = -1
|
||||
self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0)
|
||||
self.p2_mov = -1
|
||||
#self.game_state['player2_position'] = max(player2_position - (50 * self.speed), 0)
|
||||
|
||||
def predict_ball_trajectory(self, steps=60):
|
||||
|
||||
async def predict_ball_trajectory(self, steps=60):
|
||||
future_x = self.game_state['ball_position']['x']
|
||||
future_y = self.game_state['ball_position']['y']
|
||||
velocity_x = self.game_state['ball_velocity']['x']
|
||||
velocity_y = self.game_state['ball_velocity']['y']
|
||||
|
||||
for _ in range(steps):
|
||||
future_x += velocity_x
|
||||
if future_x <= 10:
|
||||
@ -101,11 +105,9 @@ class Game:
|
||||
future_x = 790
|
||||
else:
|
||||
future_y += velocity_y
|
||||
|
||||
# Dealing with bounces off walls
|
||||
if future_y <= 10 or future_y >= 390:
|
||||
velocity_y = -velocity_y # Reverse the direction of vertical movement
|
||||
|
||||
# Dealing with bounces off walls
|
||||
if future_y <= 10 or future_y >= 390:
|
||||
velocity_y = -velocity_y # Reverse the direction of vertical movement
|
||||
return {'x': future_x, 'y': future_y}
|
||||
|
||||
async def update_game_state(self):
|
||||
@ -216,8 +218,8 @@ class Game:
|
||||
async def end_game(self, disconnected_player=None):
|
||||
if not self.ended:
|
||||
self.ended = True
|
||||
if self.game_loop_task:
|
||||
self.game_loop_task.cancel()
|
||||
#if self.game_loop_task:
|
||||
# self.game_loop_task.cancel()
|
||||
print(f"- Game #{self.game_id} ENDED --- ({self})")
|
||||
|
||||
end_time = datetime.now()
|
||||
@ -233,7 +235,8 @@ class Game:
|
||||
})
|
||||
if not self.botgame:
|
||||
if not self.localgame:
|
||||
await remaining_player.send(message)
|
||||
await remaining_player.send(message)
|
||||
|
||||
# Notify both players that the game has ended
|
||||
end_message = json.dumps({
|
||||
'type': 'game_ended',
|
||||
@ -243,11 +246,15 @@ class Game:
|
||||
if not self.botgame:
|
||||
if not self.localgame:
|
||||
await self.player2.send(end_message)
|
||||
if hasattr(self, 'tournament'):
|
||||
await sync_to_async(handle_game_data)(self.game_state['player1_name'], self.game_state['player2_name'],
|
||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
||||
self.bt1, self.bt2, duration, True, self.tournament.tournoi_reg)
|
||||
else:
|
||||
await sync_to_async(handle_game_data)(self.game_state['player1_name'], self.game_state['player2_name'],
|
||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
||||
self.bt1, self.bt2, duration, False, None)
|
||||
|
||||
avd, d = (True, self.tournament.tournoi_reg) if hasattr(self, 'tournament') else (False, None)
|
||||
|
||||
await sync_to_async(handle_game_data)(self.game_state['player1_name'], self.game_state['player2_name'],
|
||||
self.game_state['player1_score'], self.game_state['player2_score'],
|
||||
self.bt1, self.bt2, duration, avd, d)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-31 16:01
|
||||
# Generated by Django 5.1.1 on 2024-09-13 11:41
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
@ -20,12 +20,6 @@ class Migration(migrations.Migration):
|
||||
('total_match', models.PositiveSmallIntegerField(default=0)),
|
||||
('total_win', models.PositiveSmallIntegerField(default=0)),
|
||||
('p_win', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('m_score_adv_match', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('best_score', models.PositiveSmallIntegerField(default=0)),
|
||||
('m_nbr_ball_touch', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('total_duration', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)),
|
||||
('m_duration', models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True)),
|
||||
('num_participated_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
('num_won_tournaments', models.PositiveSmallIntegerField(default=0)),
|
||||
],
|
||||
@ -36,7 +30,7 @@ class Migration(migrations.Migration):
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=200)),
|
||||
('nbr_player', models.PositiveSmallIntegerField()),
|
||||
('date', models.DateField()),
|
||||
('date', models.DateField(auto_now_add=True)),
|
||||
('winner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='game.player')),
|
||||
],
|
||||
),
|
||||
@ -53,7 +47,7 @@ class Migration(migrations.Migration):
|
||||
('is_tournoi', models.BooleanField()),
|
||||
('player1', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player1', to='game.player')),
|
||||
('player2', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player2', to='game.player')),
|
||||
('winner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player')),
|
||||
('winner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player')),
|
||||
('tournoi', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='matches', to='game.tournoi')),
|
||||
],
|
||||
),
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 09:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player1',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player2',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.CharField(max_length=100),
|
||||
),
|
||||
]
|
||||
@ -1,19 +0,0 @@
|
||||
# Generated by Django 5.0.7 on 2024-07-31 16:04
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player'),
|
||||
),
|
||||
]
|
||||
18
pong/game/migrations/0003_alter_tournoi_winner.py
Normal file
18
pong/game/migrations/0003_alter_tournoi_winner.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 11:56
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0002_alter_match_player1_alter_match_player2_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='winner',
|
||||
field=models.CharField(max_length=200),
|
||||
),
|
||||
]
|
||||
@ -1,4 +1,4 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-10 14:17
|
||||
# Generated by Django 5.1.1 on 2024-09-14 12:03
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
@ -6,13 +6,13 @@ from django.db import migrations, models
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0002_alter_match_winner'),
|
||||
('game', '0003_alter_tournoi_winner'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='date',
|
||||
field=models.DateField(auto_now_add=True),
|
||||
name='winner',
|
||||
field=models.CharField(blank=True, max_length=200, null=True),
|
||||
),
|
||||
]
|
||||
@ -0,0 +1,17 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-14 12:41
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0004_alter_tournoi_winner'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='player',
|
||||
name='num_won_tournaments',
|
||||
),
|
||||
]
|
||||
@ -0,0 +1,69 @@
|
||||
# Generated by Django 5.1.1 on 2024-09-15 14:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('game', '0005_remove_player_num_won_tournaments'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='best_score',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_duration',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_nbr_ball_touch',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_score_adv_match',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='m_score_match',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=5, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='num_won_tournaments',
|
||||
field=models.PositiveSmallIntegerField(default=0),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='player',
|
||||
name='total_duration',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player1',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player1', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='player2',
|
||||
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='match_as_player2', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='match',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='won_matches', to='game.player'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='tournoi',
|
||||
name='winner',
|
||||
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='game.player'),
|
||||
),
|
||||
]
|
||||
@ -11,13 +11,6 @@ from .utils import create_tournament, update_tournament, getlen
|
||||
from asgiref.sync import sync_to_async
|
||||
from .views import write_data
|
||||
|
||||
|
||||
TOURNAMENT_NAMES = [
|
||||
"Champions Clash", "Ultimate Showdown", "Battle Royale",
|
||||
"Victory Cup", "Legends Tournament", "Elite Series", "Clash of 42",
|
||||
"Shibuya incident", "Cunning Game", "Elite of the Stars"
|
||||
]
|
||||
|
||||
TOURNAMENT_NAMES = [
|
||||
"Champion's Clash", "Ultimate Showdown", "Battle Royale",
|
||||
"Victory's Cup", "Legends Tournament", "Elite Series", "Clash of 42",
|
||||
@ -90,13 +83,13 @@ class TournamentMatchMaker:
|
||||
|
||||
# Tournament start method
|
||||
async def start_tournament(self):
|
||||
|
||||
if len(self.waiting_players) < 2:
|
||||
if len(self.waiting_players) < 3:
|
||||
return False
|
||||
if len(self.waiting_players) % 2 == 0:
|
||||
await self.add_player(None)
|
||||
self.tournament_state = "in_progress"
|
||||
random.shuffle(self.waiting_players)
|
||||
'''if (len(self.waiting_players) % 2) != 0:
|
||||
print("Adding a BYE to the tournament..")
|
||||
await self.add_player(None)'''
|
||||
self.tournament_state = "in_progress"
|
||||
self.current_round = 0
|
||||
len_tournament = await sync_to_async(getlen)()
|
||||
self.final_name = self.name + " #" + str(len_tournament + 1)
|
||||
@ -105,7 +98,7 @@ class TournamentMatchMaker:
|
||||
return True
|
||||
|
||||
async def advance_tournament(self):
|
||||
players = self.waiting_players
|
||||
players = self.waiting_players
|
||||
while len(players) > 1:
|
||||
self.current_round += 1
|
||||
print(f"Starting round {self.current_round} with {len(players)} players")
|
||||
@ -188,6 +181,14 @@ class TournamentMatchMaker:
|
||||
match.game_state['player1_score'] = 3
|
||||
match.game_state['player2_score'] = 0
|
||||
await match.end_game()
|
||||
await self.send_game_text(match.player1, "You lucky bastard!\n You got an auto-win!")
|
||||
|
||||
async def send_game_text(self, player, text):
|
||||
message = json.dumps({
|
||||
'type': 'game_text_update',
|
||||
'game_text': text
|
||||
})
|
||||
await player.send(message)
|
||||
|
||||
def get_round_winners(self):
|
||||
winners = []
|
||||
@ -219,6 +220,7 @@ class TournamentMatchMaker:
|
||||
self.rounds = []
|
||||
self.current_round = 0
|
||||
self.games = 0
|
||||
self.tournament_state = "waiting"
|
||||
|
||||
async def handle_match_end(self, match):
|
||||
await self.update_brackets()
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
# /pong/game/utils.py
|
||||
|
||||
from .models import Player, Tournoi, Match
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
@ -10,10 +12,14 @@ def handle_game_data(p1, p2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tour
|
||||
player_1 = get_or_create_player(p1)
|
||||
player_2 = get_or_create_player(p2)
|
||||
|
||||
print("CHAKU & THEOUCHE are the BEST")
|
||||
create_match(player_1, player_2, s_p1, s_p2, bt_p1, bt_2, dur, is_tournoi, name_tournament)
|
||||
print("and ADRIANO is the PEST")
|
||||
|
||||
update_player_statistics(p1)
|
||||
print("UPDATE PLAYER 1")
|
||||
update_player_statistics(p2)
|
||||
print("UPDATE PLAYER 2")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in endfortheouche: {e}")
|
||||
@ -65,6 +71,7 @@ def create_player(
|
||||
m_duration=m_duration,
|
||||
num_participated_tournaments=num_participated_tournaments,
|
||||
num_won_tournaments=num_won_tournaments
|
||||
|
||||
)
|
||||
player.save()
|
||||
return player
|
||||
@ -98,10 +105,14 @@ def create_match(player1, player2, score_player1, score_player2, nbr_ball_touch_
|
||||
return match
|
||||
|
||||
def update_player_statistics(player_name):
|
||||
print(f"HERE for {player_name} §§§§§§§§§§§§")
|
||||
player = get_object_or_404(Player, name=player_name)
|
||||
print(f"GET PLAYER {player.name} !!!!!!")
|
||||
|
||||
matches_as_player1 = Match.objects.filter(player1=player)
|
||||
#print(f"GET MATCH AS PLAYER 1 {matches_as_player1.player1.name} !!!!!!")
|
||||
matches_as_player2 = Match.objects.filter(player2=player)
|
||||
#print(f"GET MATCH AS PLAYER 2 {matches_as_player2.player2.name} !!!!!!")
|
||||
|
||||
total_match = matches_as_player1.count() + matches_as_player2.count()
|
||||
|
||||
@ -122,13 +133,13 @@ def update_player_statistics(player_name):
|
||||
return
|
||||
|
||||
won_matches = Match.objects.filter(winner=player)
|
||||
#part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player1=player)
|
||||
#part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__matches_as_player2=player)
|
||||
#won_tourn = Tournoi.objects.filter(winner=player)
|
||||
part_tourn_as_p1 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player1=player)
|
||||
part_tourn_as_p2 = Tournoi.objects.filter(matches__is_tournoi=True, matches__player2=player)
|
||||
won_tourn = Tournoi.objects.filter(winner=player)
|
||||
|
||||
total_score = matches_as_player1.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
total_score += matches_as_player2.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
|
||||
|
||||
total_score_adv = matches_as_player1.aggregate(Sum('score_player2'))['score_player2__sum'] or 0
|
||||
total_score_adv += matches_as_player2.aggregate(Sum('score_player1'))['score_player1__sum'] or 0
|
||||
|
||||
@ -146,9 +157,9 @@ def update_player_statistics(player_name):
|
||||
total_duration += matches_as_player2.aggregate(Sum('duration'))['duration__sum'] or 0
|
||||
m_duration = total_duration / total_match
|
||||
|
||||
#total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
#total_win_tourn = won_tourn.count()
|
||||
#p_win_tourn = (total_win_tourn / total_tourn_p) * 100 if total_tourn_p else 0
|
||||
total_tourn_p = part_tourn_as_p1.count() + part_tourn_as_p2.count()
|
||||
total_win_tourn = won_tourn.count()
|
||||
p_win_tourn = (total_win_tourn / total_tourn_p) * 100 if total_tourn_p else 0
|
||||
|
||||
best_score_as_player1 = matches_as_player1.aggregate(Max('score_player1'))['score_player1__max'] or 0
|
||||
best_score_as_player2 = matches_as_player2.aggregate(Max('score_player2'))['score_player2__max'] or 0
|
||||
@ -163,8 +174,8 @@ def update_player_statistics(player_name):
|
||||
player.m_nbr_ball_touch = m_nbr_ball_touch
|
||||
player.total_duration = total_duration
|
||||
player.m_duration = m_duration
|
||||
# player.num_participated_tournaments = total_tourn_p
|
||||
#player.num_won_tournaments = total_win_tourn
|
||||
player.num_participated_tournaments = total_tourn_p
|
||||
player.num_won_tournaments = total_win_tourn
|
||||
|
||||
player.save()
|
||||
|
||||
@ -193,4 +204,4 @@ def update_tournament(name_tournoi, winner_name):
|
||||
|
||||
|
||||
def getlen():
|
||||
return Tournoi.objects.count()
|
||||
return Tournoi.objects.count()
|
||||
@ -91,15 +91,22 @@ def player_list_json(request):
|
||||
}
|
||||
return JsonResponse(data)
|
||||
|
||||
def tournoi_list_json(request):
|
||||
tournois = Tournoi.objects.all()
|
||||
|
||||
data = {
|
||||
'tournois': list(tournois.values(
|
||||
'id', 'name', 'nbr_player', 'date', 'winner'
|
||||
))
|
||||
def get_tournoi_data(tournoi):
|
||||
return {
|
||||
"id": tournoi.id,
|
||||
"name": tournoi.name,
|
||||
"nbr_player": tournoi.nbr_player,
|
||||
"date": tournoi.date,
|
||||
"winner": {
|
||||
"id": tournoi.winner.id,
|
||||
"name": tournoi.winner.name
|
||||
} if tournoi.winner else None
|
||||
}
|
||||
return JsonResponse(data)
|
||||
|
||||
def tournoi_list_json(request):
|
||||
tournois = Tournoi.objects.select_related('winner').all() # Charge les données du gagnant
|
||||
tournois_data = [get_tournoi_data(tournoi) for tournoi in tournois]
|
||||
return JsonResponse({"tournois": tournois_data})
|
||||
|
||||
|
||||
import os
|
||||
|
||||
@ -13,7 +13,6 @@ from pathlib import Path
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
|
||||
|
||||
@ -29,14 +28,15 @@ ALLOWED_HOSTS = ['*']
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
#'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
#'django.contrib.sessions',
|
||||
#'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'channels',
|
||||
'pong.game',
|
||||
#'django_db_conn_pool',
|
||||
'rest_framework'
|
||||
]
|
||||
|
||||
@ -46,7 +46,7 @@ MIDDLEWARE = [
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
#'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
@ -81,6 +81,7 @@ DATABASES = {
|
||||
'PASSWORD': os.getenv('DB_PASSWORD'),
|
||||
'HOST': os.getenv('DB_HOST'),
|
||||
'PORT': '5432',
|
||||
'CONN_MAX_AGE': None,
|
||||
}
|
||||
}
|
||||
|
||||
@ -136,6 +137,32 @@ CHANNEL_LAYERS = {
|
||||
},
|
||||
}
|
||||
|
||||
LOGGING = {
|
||||
'version': 1, # Django requires this key
|
||||
'disable_existing_loggers': False, # Keep Django's default loggers
|
||||
'formatters': {
|
||||
'simple': {
|
||||
'format': '{levelname} {message}',
|
||||
'style': '{', # Allows to use Python's new style string formatting
|
||||
},
|
||||
},
|
||||
'handlers': {
|
||||
'console': { # Log to the console
|
||||
'level': 'DEBUG', # Minimum level of messages that should be handled
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'simple', # Use the simple formatter defined above
|
||||
},
|
||||
},
|
||||
'loggers': {
|
||||
'django': { # The main logger for Django itself
|
||||
'handlers': ['console'],
|
||||
'level': 'DEBUG', # Minimum log level to be logged
|
||||
'propagate': False, # Prevents log propagation to other loggers
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
"""
|
||||
LOGGING = {
|
||||
'version': 1, # The version of the logging configuration schema
|
||||
'disable_existing_loggers': False, # Allows existing loggers to keep logging
|
||||
@ -170,3 +197,4 @@ LOGGING = {
|
||||
},
|
||||
},
|
||||
}
|
||||
"""
|
||||
|
||||
@ -103,10 +103,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying matches:');
|
||||
const matchListBody = document.querySelector('#match-list tbody');
|
||||
matchListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
|
||||
if (matches.length != 0) {
|
||||
matches.forEach(match => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${match.id}</td>
|
||||
<td>${match.player1__name}</td>
|
||||
@ -124,6 +125,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
matchListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
`;
|
||||
@ -135,10 +137,11 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying players:');
|
||||
const playersListBody = document.querySelector('#player-list tbody');
|
||||
playersListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
|
||||
if (players.length != 0) {
|
||||
players.forEach(player => {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${player.id}</td>
|
||||
<td>${player.name}</td>
|
||||
@ -157,8 +160,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
playersListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
<td colspan="12">No player found.</td>
|
||||
`
|
||||
playersListBody.appendChild(row);
|
||||
}
|
||||
@ -168,22 +172,25 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
console.log('Displaying tournois:');
|
||||
const tournoisListBody = document.querySelector('#tournoi-list tbody');
|
||||
tournoisListBody.innerHTML = '';
|
||||
const row = document.createElement('tr');
|
||||
|
||||
if (tournois.length != 0) {
|
||||
tournois.forEach(tournoi => {
|
||||
console.log('Winner:', tournoi.winner); //debug !!!!!!!!!!!!!!!!!
|
||||
console.log('Winner:', tournoi.winner__name); //debug !!!!!!!!!!!!!!!!!
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td>${tournoi.id}</td>
|
||||
<td>${tournoi.name}</td>
|
||||
<td>${tournoi.nbr_player}</td>
|
||||
<td>${tournoi.date}</td>
|
||||
<td>${tournoi.winner ? tournoi.winner.name : 'None'}</td>
|
||||
<td>${tournoi.winner ? tournoi.winner.name : 'No one yet ...'}</td>
|
||||
`;
|
||||
tournoisListBody.appendChild(row);
|
||||
});
|
||||
} else {
|
||||
const row = document.createElement('tr');
|
||||
row.innerHTML = `
|
||||
<td colspan="12">No matches found.</td>
|
||||
<td colspan="12">No tournoi found.</td>
|
||||
`
|
||||
tournoisListBody.appendChild(row);
|
||||
}
|
||||
|
||||
BIN
pong/static/favicon.ico
Normal file
BIN
pong/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@ -360,7 +360,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
}
|
||||
|
||||
function startWebSocketConnection(token, players) {
|
||||
socket = new WebSocket(`ws://${window.location.host}/ws/game/`);
|
||||
socket = new WebSocket(`wss://${window.location.host}/ws/game/`);
|
||||
|
||||
socket.onopen = function (event) {
|
||||
console.log('WebSocket connection established');
|
||||
@ -388,6 +388,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
} else if (data.type === 'game_state_update') {
|
||||
updateGameState(data.game_state);
|
||||
} else if (data.type === 'game_text_update') {
|
||||
updateGameText(data.game_text);
|
||||
} else if (data.type === 'player_disconnected') {
|
||||
console.log('Player disconnected:', data.player);
|
||||
} else if (data.type === 'game_ended') {
|
||||
@ -462,6 +464,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.getElementById('game-text').textContent = gameState.game_text;
|
||||
}
|
||||
|
||||
function updateGameText(gameText) {
|
||||
document.getElementById('game-text').textContent = gameText;
|
||||
}
|
||||
|
||||
const starsContainer = document.getElementById('stars');
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const star = document.createElement('div');
|
||||
|
||||
@ -7,9 +7,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pong Game</title>
|
||||
<link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}?v=3">
|
||||
<div class="logo">
|
||||
<img src="{% static 'logo-42-perpignan.png' %}" alt="Logo">
|
||||
</div>
|
||||
<link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}?v=2" >
|
||||
<div class="logo">
|
||||
<img src="{% static 'logo-42-perpignan.png' %}" alt="Logo">
|
||||
</div>
|
||||
</head>
|
||||
<body>
|
||||
<div class="language-switcher">
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
django
|
||||
psycopg2
|
||||
django>=3.2
|
||||
psycopg[binary]
|
||||
python-dotenv
|
||||
channels
|
||||
daphne
|
||||
djangorestframework
|
||||
web3
|
||||
python-json-logger==2.0.7
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user