multiple pong party simultaneously (remove react strict mode), matchmaking done

This commit is contained in:
kinou-p 2023-04-28 17:47:52 +02:00
parent 77ebe2c24e
commit da6a8041c7
45 changed files with 2819 additions and 4738 deletions

5341
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
"private": true, "private": true,
"license": "UNLICENSED", "license": "UNLICENSED",
"scripts": { "scripts": {
"build": "nest build --webpack", "build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start", "start": "nest start",
"start:dev": "nest start --watch", "start:dev": "nest start --watch",
@ -20,10 +20,12 @@
"test:e2e": "jest --config ./test/jest-e2e.json" "test:e2e": "jest --config ./test/jest-e2e.json"
}, },
"dependencies": { "dependencies": {
"@nestjs/axios": "^2.0.0",
"@nestjs/common": "^9.0.0", "@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0", "@nestjs/core": "^9.0.0",
"@nestjs/platform-express": "^9.0.0", "@nestjs/platform-express": "^9.0.0",
"@nestjs/typeorm": "^9.0.1", "@nestjs/typeorm": "^9.0.1",
"axios": "^1.3.5",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"pg": "^8.10.0", "pg": "^8.10.0",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",

View File

@ -1,7 +1,11 @@
import { Body, Controller, Get, Post } from '@nestjs/common'; import { Body, Controller, Get, Post, Query, InternalServerErrorException } from '@nestjs/common';
// import { AppService } from './app.service.js'; // import { AppService } from './app.service.js';
import { UsersService } from './app.service'; import { UsersService } from './app.service';
import { User } from './model/item.entity'; import { User } from './model/item.entity';
// import { HttpService } from '@nestjs/common';
// import { HttpService } from '@nestjs/axios'
import axios from 'axios';
import { AxiosResponse } from 'axios';
@Controller() @Controller()
@ -15,23 +19,37 @@ export class AppController2 {
} }
@Controller('api') @Controller('api')
export class AppController { export class AppController
{
constructor(private readonly usersService: UsersService) {} constructor(private readonly usersService: UsersService) {}
// constructor(private readonly appService: AppService) {}
@Get('login') @Post('token')
getHello(): string { async getToken(@Body('code') code: string): Promise<any>
return this.usersService.getHello(); {
const http = axios;
console.log(`here is the code= ${code}`);
const data = {
grant_type: 'authorization_code',
client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
client_secret: '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',
code: code,
redirect_uri: 'http://localhost:8080/login42',
};
try {
const response: AxiosResponse = await http.post('https://api.intra.42.fr/oauth/token', data);
// console.log(`response= ${response}`);
return response;
} }
catch (error)
{
console.error(error);
throw new InternalServerErrorException('Failed to get access token');
}
}
@Post('login') @Post('login')
async create(@Body() user: User) { async create(@Body() user: User)
{
return this.usersService.create(user); return this.usersService.create(user);
} }
// @Get('test')
// getHello(): string {
// return this.appService.getHello();
// }
} }
// "clean": "rm -rf /usr/src/app/src && rm -rf /usr/src/app/model && rm -rf /usr/src/app/config && rm -rf *.ts",

View File

@ -2,7 +2,16 @@ import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule, {
cors: {
origin: '*',
methods: '*',
// preflightContinue: false,
// optionsSuccessStatus: 204,
// credentials: true,
allowedHeaders: '*',
},
});
await app.listen(3000); await app.listen(3000);
} }
bootstrap(); bootstrap();

View File

@ -31,32 +31,32 @@
// } // }
// base.entity.ts // base.entity.ts
// @PrimaryGeneratedColumn('uuid')
// id: string;
// @Column({ type: 'boolean', default: true })
// isActive: boolean;
// @Column({ type: 'boolean', default: false })
// isArchived: boolean;
// @CreateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// createDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// createdBy: string;
// @UpdateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// lastChangedDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// lastChangedBy: string;
// @Column({ type: 'varchar', length: 300, nullable: true })
// internalComment: string | null;
import { PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm'; import { PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm';
export abstract class BaseEntity { export abstract class BaseEntity {
// @PrimaryGeneratedColumn('uuid')
// id: string;
// @Column({ type: 'boolean', default: true })
// isActive: boolean;
// @Column({ type: 'boolean', default: false })
// isArchived: boolean;
// @CreateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// createDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// createdBy: string;
// @UpdateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// lastChangedDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// lastChangedBy: string;
// @Column({ type: 'varchar', length: 300, nullable: true })
// internalComment: string | null;
@PrimaryGeneratedColumn() @PrimaryGeneratedColumn()
id: number; id: number;

View File

@ -2,7 +2,7 @@
import { Entity, Column } from 'typeorm'; import { Entity, Column } from 'typeorm';
import { BaseEntity } from './base.entity'; import { BaseEntity } from './base.entity';
@Entity({ name: 'user' }) @Entity({ name: 'User' })
export class User extends BaseEntity { export class User extends BaseEntity {
@Column({ type: 'varchar', length: 300 , nullable: true}) @Column({ type: 'varchar', length: 300 , nullable: true})

View File

@ -47,15 +47,24 @@ server {
proxy_pass http://react_app:8080; proxy_pass http://react_app:8080;
} }
location /api/login { location /api {
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://backend:3000; proxy_pass http://backend:3000/api;
} }
# location /api {
# 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;
# proxy_pass http://backend:3000/api;
# }
#proxy_pass http://localhost:5000 #proxy_pass http://localhost:5000
} }

View File

@ -3,9 +3,7 @@ version: "3.3"
services: services:
nginx: nginx:
build: image: nginx:alpine
context : ./
dockerfile: ./dockerfiles/Dockerfile.nginx
container_name: nginx container_name: nginx
env_file: .env env_file: .env
depends_on: depends_on:
@ -13,12 +11,11 @@ services:
ports: ports:
- 80:80 - 80:80
volumes: volumes:
- ./conf/nginx.conf:/etc/nginx/conf.d/default.conf
- ./frontend:/var/www/html - ./frontend:/var/www/html
# - ./conf/nginx.conf /etc/nginx/conf.d/default.conf
networks: networks:
- pongNetwork - pongNetwork
react_app: react_app:
image: node:latest image: node:latest
container_name: react_app container_name: react_app
@ -28,7 +25,7 @@ services:
ports: ports:
- 8080:8080 - 8080:8080
volumes: volumes:
- ./frontend/pong/my-app:/app - ./frontend:/app
networks: networks:
- pongNetwork - pongNetwork
entrypoint: ["sh", "-c" , "npm install && npm run start:dev"] entrypoint: ["sh", "-c" , "npm install && npm run start:dev"]
@ -82,6 +79,20 @@ services:
- ./pong:/app - ./pong:/app
entrypoint: ["sh", "-c" , "npm install && npm run start:dev"] entrypoint: ["sh", "-c" , "npm install && npm run start:dev"]
# chat:
# image: node:latest
# container_name: chat
# working_dir: /app
# ports:
# - 4001:4001
# env_file: .env
# networks:
# - pongNetwork
# volumes:
# - ./chat:/app
# entrypoint: ["sh", "-c" , "npm install && npm run start:dev"]
networks: networks:
pongNetwork: pongNetwork:
driver: bridge driver: bridge

View File

@ -1,121 +0,0 @@
body {
margin: 0%;
background-color: rgb(47, 47, 47);
color: white;
}
footer {
text-align: center;
position: absolute;
bottom: 0;
width: 100%;
background-color: rgb(0, 0, 0);
}
.pp {
height: 10vh;
width: 10vh;
border-radius: 50%;
}
.loginHere{
font-size: 5vh;
font-family: 'Rubik Iso';
text-align: center;
margin-top: 10vh;
}
::placeholder {
font-size: 3vh;
text-align: center;
align-items: center;
margin:auto;
}
.submit{
height: 5vh;
border-radius: 100vh;
}
.submit:hover {
background-color: blueviolet;
}
input{
height: 5vh;
border-radius: 100vh;
}
.pp:hover {
border: 5px solid rgb(255, 255, 255);
}
.userTxt:hover {
color:blueviolet;;
}
.userTxt {
margin-right: 5%;
}
.username {
display: flex;
font-size: 4vh;
max-width: 33%;
color: aqua;
justify-content: right;
}
label{
}
.login {
}
.loginForm {
align-items: center;
height: 50vh;
display: flex;
flex-direction: column;
justify-content: space-around;
}
.menu {
color: aqua;
font-size: 4vh;
}
.pong{
font-family:'Rubik Iso';
}
.box {
width: 33%;
}
.center {
align-self: center;
}
.headerName {
display:flex;
max-width: 33%;
height: 100%;
font-size: 50px;
color:blueviolet;
font-size: 12vh;
justify-content: center;
}
.header {
display: flex;
margin: 0;
height: 15vh;
align-items: center;
background-color: rgb(0, 0, 0);
}
h1 {
color:blueviolet
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

View File

@ -1,4 +0,0 @@
[ZoneTransfer]
ZoneId=3
ReferrerUrl=https://www.google.com/
HostUrl=https://img.ev.mu/images/articles/600x/775102.jpg

View File

@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<link href="./css/header.css" rel="stylesheet">
<title>BEST PONG EVER</title>
<script src="./js/login.js"></script>
</head>
<body>
<div class="header">
<div class="box menu"> <p class="userTxt">Menu</p> </div>
<div class="box headerName">
<p class="center pong">PONG</p>
</div>
<div class="box username">
<p class="userTxt">UserName</p>
<img class="pp center" src="./img/pp.jpg" alt="profile picture">
</div>
</div>
<div class ="login">
<form id="loginForm" method="post" name="login" action="/api/login" class ="loginForm">
<p class="loginHere">Login Here</p>
<input type="text" name="nickname" placeholder="login">
<input type="text" name="password" placeholder="password">
<button class="submit" onclick="login()">LOGIN</button>
</form>
<button></button>
</div>
<footer>
<p>@apommier | apommier@student.42.fr</p>
</footer>
</body>
</html>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rubik+Iso&display=swap" rel="stylesheet">

View File

@ -1,6 +0,0 @@
function login()
{
alert("Le bouton a été cliqué !");
var formulaire = document.getElementById("loginForm");
formulaire.submit();
}

View File

@ -11,6 +11,7 @@
"@testing-library/jest-dom": "^5.16.5", "@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"axios": "^1.3.5",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-router-dom": "^6.10.0", "react-router-dom": "^6.10.0",
@ -4199,14 +4200,14 @@
"integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==" "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA=="
}, },
"node_modules/@typescript-eslint/eslint-plugin": { "node_modules/@typescript-eslint/eslint-plugin": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.0.tgz",
"integrity": "sha512-vxHvLhH0qgBd3/tW6/VccptSfc8FxPQIkmNTVLWcCOVqSBvqpnKkBTYrhcGlXfSnd78azwe+PsjYFj0X34/njA==", "integrity": "sha512-p0QgrEyrxAWBecR56gyn3wkG15TJdI//eetInP3zYRewDh0XS+DhB3VUAd3QqvziFsfaQIoIuZMxZRB7vXYaYw==",
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.4.0", "@eslint-community/regexpp": "^4.4.0",
"@typescript-eslint/scope-manager": "5.58.0", "@typescript-eslint/scope-manager": "5.59.0",
"@typescript-eslint/type-utils": "5.58.0", "@typescript-eslint/type-utils": "5.59.0",
"@typescript-eslint/utils": "5.58.0", "@typescript-eslint/utils": "5.59.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"grapheme-splitter": "^1.0.4", "grapheme-splitter": "^1.0.4",
"ignore": "^5.2.0", "ignore": "^5.2.0",
@ -4232,11 +4233,11 @@
} }
}, },
"node_modules/@typescript-eslint/experimental-utils": { "node_modules/@typescript-eslint/experimental-utils": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/experimental-utils/-/experimental-utils-5.59.0.tgz",
"integrity": "sha512-LA/sRPaynZlrlYxdefrZbMx8dqs/1Kc0yNG+XOk5CwwZx7tTv263ix3AJNioF0YBVt7hADpAUR20owl6pv4MIQ==", "integrity": "sha512-evvdzcPrUv9+Hj+KX6fa3WMrtTZ7onnGHL3NfT/zN9q2FQhb2yvNJDa+w/ND0TpdRCbulwag0dxwMUt2MJB2Vg==",
"dependencies": { "dependencies": {
"@typescript-eslint/utils": "5.58.0" "@typescript-eslint/utils": "5.59.0"
}, },
"engines": { "engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0" "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
@ -4250,13 +4251,13 @@
} }
}, },
"node_modules/@typescript-eslint/parser": { "node_modules/@typescript-eslint/parser": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.0.tgz",
"integrity": "sha512-ixaM3gRtlfrKzP8N6lRhBbjTow1t6ztfBvQNGuRM8qH1bjFFXIJ35XY+FC0RRBKn3C6cT+7VW1y8tNm7DwPHDQ==", "integrity": "sha512-qK9TZ70eJtjojSUMrrEwA9ZDQ4N0e/AuoOIgXuNBorXYcBDk397D2r5MIe1B3cok/oCtdNC5j+lUUpVB+Dpb+w==",
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "5.58.0", "@typescript-eslint/scope-manager": "5.59.0",
"@typescript-eslint/types": "5.58.0", "@typescript-eslint/types": "5.59.0",
"@typescript-eslint/typescript-estree": "5.58.0", "@typescript-eslint/typescript-estree": "5.59.0",
"debug": "^4.3.4" "debug": "^4.3.4"
}, },
"engines": { "engines": {
@ -4276,12 +4277,12 @@
} }
}, },
"node_modules/@typescript-eslint/scope-manager": { "node_modules/@typescript-eslint/scope-manager": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.59.0.tgz",
"integrity": "sha512-b+w8ypN5CFvrXWQb9Ow9T4/6LC2MikNf1viLkYTiTbkQl46CnR69w7lajz1icW0TBsYmlpg+mRzFJ4LEJ8X9NA==", "integrity": "sha512-tsoldKaMh7izN6BvkK6zRMINj4Z2d6gGhO2UsI8zGZY3XhLq1DndP3Ycjhi1JwdwPRwtLMW4EFPgpuKhbCGOvQ==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "5.58.0", "@typescript-eslint/types": "5.59.0",
"@typescript-eslint/visitor-keys": "5.58.0" "@typescript-eslint/visitor-keys": "5.59.0"
}, },
"engines": { "engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0" "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
@ -4292,12 +4293,12 @@
} }
}, },
"node_modules/@typescript-eslint/type-utils": { "node_modules/@typescript-eslint/type-utils": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-5.59.0.tgz",
"integrity": "sha512-FF5vP/SKAFJ+LmR9PENql7fQVVgGDOS+dq3j+cKl9iW/9VuZC/8CFmzIP0DLKXfWKpRHawJiG70rVH+xZZbp8w==", "integrity": "sha512-d/B6VSWnZwu70kcKQSCqjcXpVH+7ABKH8P1KNn4K7j5PXXuycZTPXF44Nui0TEm6rbWGi8kc78xRgOC4n7xFgA==",
"dependencies": { "dependencies": {
"@typescript-eslint/typescript-estree": "5.58.0", "@typescript-eslint/typescript-estree": "5.59.0",
"@typescript-eslint/utils": "5.58.0", "@typescript-eslint/utils": "5.59.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"tsutils": "^3.21.0" "tsutils": "^3.21.0"
}, },
@ -4318,9 +4319,9 @@
} }
}, },
"node_modules/@typescript-eslint/types": { "node_modules/@typescript-eslint/types": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.59.0.tgz",
"integrity": "sha512-JYV4eITHPzVQMnHZcYJXl2ZloC7thuUHrcUmxtzvItyKPvQ50kb9QXBkgNAt90OYMqwaodQh2kHutWZl1fc+1g==", "integrity": "sha512-yR2h1NotF23xFFYKHZs17QJnB51J/s+ud4PYU4MqdZbzeNxpgUr05+dNeCN/bb6raslHvGdd6BFCkVhpPk/ZeA==",
"engines": { "engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0" "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}, },
@ -4330,12 +4331,12 @@
} }
}, },
"node_modules/@typescript-eslint/typescript-estree": { "node_modules/@typescript-eslint/typescript-estree": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.59.0.tgz",
"integrity": "sha512-cRACvGTodA+UxnYM2uwA2KCwRL7VAzo45syNysqlMyNyjw0Z35Icc9ihPJZjIYuA5bXJYiJ2YGUB59BqlOZT1Q==", "integrity": "sha512-sUNnktjmI8DyGzPdZ8dRwW741zopGxltGs/SAPgGL/AAgDpiLsCFLcMNSpbfXfmnNeHmK9h3wGmCkGRGAoUZAg==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "5.58.0", "@typescript-eslint/types": "5.59.0",
"@typescript-eslint/visitor-keys": "5.58.0", "@typescript-eslint/visitor-keys": "5.59.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"globby": "^11.1.0", "globby": "^11.1.0",
"is-glob": "^4.0.3", "is-glob": "^4.0.3",
@ -4356,16 +4357,16 @@
} }
}, },
"node_modules/@typescript-eslint/utils": { "node_modules/@typescript-eslint/utils": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-5.59.0.tgz",
"integrity": "sha512-gAmLOTFXMXOC+zP1fsqm3VceKSBQJNzV385Ok3+yzlavNHZoedajjS4UyS21gabJYcobuigQPs/z71A9MdJFqQ==", "integrity": "sha512-GGLFd+86drlHSvPgN/el6dRQNYYGOvRSDVydsUaQluwIW3HvbXuxyuD5JETvBt/9qGYe+lOrDk6gRrWOHb/FvA==",
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/eslint-utils": "^4.2.0",
"@types/json-schema": "^7.0.9", "@types/json-schema": "^7.0.9",
"@types/semver": "^7.3.12", "@types/semver": "^7.3.12",
"@typescript-eslint/scope-manager": "5.58.0", "@typescript-eslint/scope-manager": "5.59.0",
"@typescript-eslint/types": "5.58.0", "@typescript-eslint/types": "5.59.0",
"@typescript-eslint/typescript-estree": "5.58.0", "@typescript-eslint/typescript-estree": "5.59.0",
"eslint-scope": "^5.1.1", "eslint-scope": "^5.1.1",
"semver": "^7.3.7" "semver": "^7.3.7"
}, },
@ -4401,11 +4402,11 @@
} }
}, },
"node_modules/@typescript-eslint/visitor-keys": { "node_modules/@typescript-eslint/visitor-keys": {
"version": "5.58.0", "version": "5.59.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.58.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.59.0.tgz",
"integrity": "sha512-/fBraTlPj0jwdyTwLyrRTxv/3lnU2H96pNTVM6z3esTWLtA5MZ9ghSMJ7Rb+TtUAdtEw9EyJzJ0EydIMKxQ9gA==", "integrity": "sha512-qZ3iXxQhanchCeaExlKPV3gDQFxMUmU35xfd5eCXB6+kUw1TUAbIy2n7QIrwz9s98DQLzNWyHp61fY0da4ZcbA==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "5.58.0", "@typescript-eslint/types": "5.59.0",
"eslint-visitor-keys": "^3.3.0" "eslint-visitor-keys": "^3.3.0"
}, },
"engines": { "engines": {
@ -4991,13 +4992,36 @@
} }
}, },
"node_modules/axe-core": { "node_modules/axe-core": {
"version": "4.6.3", "version": "4.7.0",
"resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.6.3.tgz", "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.7.0.tgz",
"integrity": "sha512-/BQzOX780JhsxDnPpH4ZiyrJAzcd8AfzFPkv+89veFSr1rcMjuq2JDCwypKaPeB6ljHp9KjXhPpjgCvQlWYuqg==", "integrity": "sha512-M0JtH+hlOL5pLQwHOLNYZaXuhqmvS8oExsqB1SBYgA4Dk7u/xx+YdGHXaK5pyUfed5mYXdlYiphWq3G8cRi5JQ==",
"engines": { "engines": {
"node": ">=4" "node": ">=4"
} }
}, },
"node_modules/axios": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.3.5.tgz",
"integrity": "sha512-glL/PvG/E+xCWwV8S6nCHcrfg1exGx7vxyUIivIA1iL7BIh6bePylCfVHwp6k13ao7SATxB6imau2kqY+I67kw==",
"dependencies": {
"follow-redirects": "^1.15.0",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/axios/node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/axobject-query": { "node_modules/axobject-query": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.1.1.tgz", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.1.1.tgz",
@ -14130,6 +14154,11 @@
"node": ">= 0.10" "node": ">= 0.10"
} }
}, },
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/psl": { "node_modules/psl": {
"version": "1.9.0", "version": "1.9.0",
"resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz",
@ -14779,11 +14808,11 @@
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==" "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ=="
}, },
"node_modules/resolve": { "node_modules/resolve": {
"version": "1.22.3", "version": "1.22.2",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.3.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.2.tgz",
"integrity": "sha512-P8ur/gp/AmbEzjr729bZnLjXK5Z+4P0zhIJgBgzqRih7hL7BOukHGtSTA3ACMY467GRFz3duQsi0bDZdR7DKdw==", "integrity": "sha512-Sb+mjNHOULsBv818T40qSPeRiuWLyaGMa5ewydRLFimneixmVy2zdivRl+AF6jaYPC8ERxGDmFSiqui6SfPd+g==",
"dependencies": { "dependencies": {
"is-core-module": "^2.12.0", "is-core-module": "^2.11.0",
"path-parse": "^1.0.7", "path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0" "supports-preserve-symlinks-flag": "^1.0.0"
}, },
@ -15136,9 +15165,9 @@
} }
}, },
"node_modules/semver": { "node_modules/semver": {
"version": "7.4.0", "version": "7.5.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.4.0.tgz", "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.0.tgz",
"integrity": "sha512-RgOxM8Mw+7Zus0+zcLEUn8+JfoLpj/huFTItQy2hsM4khuC1HYRDp0cU482Ewn/Fcy6bCjufD8vAj7voC66KQw==", "integrity": "sha512-+XC0AD/R7Q2mPSRuy2Id0+CGTZ98+8f+KvwirxOKIEyid+XSx6HbC63p+O4IndTHuX5Z+JxQ0TghCkO5Cg/2HA==",
"dependencies": { "dependencies": {
"lru-cache": "^6.0.0" "lru-cache": "^6.0.0"
}, },

View File

@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^5.16.5", "@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0", "@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^13.5.0",
"axios": "^1.3.5",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-router-dom": "^6.10.0", "react-router-dom": "^6.10.0",
@ -15,6 +16,7 @@
}, },
"scripts": { "scripts": {
"start": "HOST=0.0.0.0 PORT=8080 react-scripts start", "start": "HOST=0.0.0.0 PORT=8080 react-scripts start",
"start:dev": "npm run start --watch",
"build": "react-scripts build", "build": "react-scripts build",
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject" "eject": "react-scripts eject"

View File

@ -1,38 +0,0 @@
import { useEffect } from 'react';
import { drawCanvas } from './canvas.js';
import '../styles/field.css';
function Field()
{
useEffect(() => {
drawCanvas();
}, []);
return (
<div class="field" id="canvas_container">
<canvas id="myCanvas"></canvas>
</div>
);
}
export default Field;
// function draw() {
// // Effacer le canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// // Dessiner la raquette
// ctx.fillRect(canvas.width - paddleWidth, paddleY, paddleWidth, paddleHeight);
// // Appeler la fonction draw à chaque frame
// requestAnimationFrame(draw);
// }
// draw(); // Appeler la fonction draw pour la première fois
// const canvas = document.getElementById('myCanvas');
// canvas.width = 500;
// canvas.height = 500;
// const ctx = canvas.getContext('2d');
// ctx.fillRect(50, 50, 1000, 1000);

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,20 @@
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import ChatPage from './components/ChatPage';
import socketIO from 'socket.io-client';
const socket = socketIO.connect('http://localhost:4000');
function App() {
return (
<BrowserRouter>
<div>
<Routes>
<Route path="/" element={<Home socket={socket} />}></Route>
<Route path="/chat" element={<ChatPage socket={socket} />}></Route>
</Routes>
</div>
</BrowserRouter>
);
}
export default App;

View File

@ -0,0 +1,72 @@
import { useEffect } from 'react';
import { useState, useRef } from 'react';
import { drawCanvas } from './canvas.js';
import '../styles/field.css';
function Field()
{
useEffect(() => {
console.log("launch canva hehe")
drawCanvas();
}, []);
// const [buttonClicked, setButtonClicked] = useState(false);
// const handleButtonClick = () => {
// drawCanvas();
// setButtonClicked(true);
// };
return (
<div class="field" id="canvas_container">
<canvas id="myCanvas"></canvas>
{/* <button onClick={handleButtonClick}>Draw on Canvas</button> */}
{/* {buttonClicked && <canvas id="myCanvas"></canvas>}
{!buttonClicked && <button onClick={handleButtonClick}>Draw on Canvas</button>} */}
</div>
);
}
export default Field;
// function Field() {
// const [buttonClicked, setButtonClicked] = useState(false);
// const handleButtonClick = () => {
// const canvas = document.createElement('canvas');
// canvas.id = 'myCanvas';
// console.log("button clicked")
// document.getElementById('canvas_container').appendChild(canvas);
// setButtonClicked(true);
// drawCanvas(canvas);
// };
// setButtonClicked(true);
// return (
// // <div className="field" id="canvas_container">
// <div className={`notClicked ${buttonClicked ? 'clicked' : ''}`} id="canvas_container">
// {!buttonClicked && <button className="playButton" onClick={handleButtonClick}>Play</button>}
// </div>
// );
// }
// export default Field;
// function draw() {
// // Effacer le canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// // Dessiner la raquette
// ctx.fillRect(canvas.width - paddleWidth, paddleY, paddleWidth, paddleHeight);
// // Appeler la fonction draw à chaque frame
// requestAnimationFrame(draw);
// }
// draw(); // Appeler la fonction draw pour la première fois
// const canvas = document.getElementById('myCanvas');
// canvas.width = 500;
// canvas.height = 500;
// const ctx = canvas.getContext('2d');
// ctx.fillRect(50, 50, 1000, 1000);

View File

@ -8,7 +8,8 @@ function Header()
<div class="header"> <div class="header">
<a href="http://localhost" class="box menu"> <p class="userTxt">Menu</p> </a> <a href="http://localhost" class="box menu"> <p class="userTxt">Menu</p> </a>
<div class="box headerName"> <div class="box headerName">
<p class="center pong">PONG</p> <a href="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin42&response_type=code"
class="center pong">PONG</a>
</div> </div>
<a href="http://localhost/pong" class="box username"> <a href="http://localhost/pong" class="box username">
<p class="userTxt">Play</p> <p class="userTxt">Play</p>

View File

@ -1,7 +1,6 @@
import '../styles/old.css'; import '../styles/old.css';
import { login } from '../script/login.js' import { login } from '../script/login.js'
function Home() function Home()
{ {
return ( return (
@ -12,7 +11,7 @@ function Home()
<input type="text" name="password" placeholder="password"></input> <input type="text" name="password" placeholder="password"></input>
<button class="submit" onClick={login}>LOGIN</button> <button class="submit" onClick={login}>LOGIN</button>
</form> </form>
<button></button> {/* <button></button> */}
</div> </div>
); );
} }

View File

@ -0,0 +1,43 @@
// import GoogleLogin from 'react-google-login';
import { useEffect } from 'react';
import axios from 'axios';
// import setupLogin from '../script/login42';
// import React, { useEffect } from 'react';
function Login42()
{
useEffect(() => {
console.log("you said yes to connect with 42");
const url = new URL(window.location.href);
// console.log(`url is= ${url}`);
const code = url.searchParams.get('code');
console.log(`code is= ${code}`);
const data = {
grant_type: 'authorization_code',
client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
client_secret: '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',
code: code,
redirect_uri: 'http://localhost:8080/login42',
};
axios.post('https://api.intra.42.fr/oauth/token', data)
.then(response => {
// handle success response
console.log(response);
})
.catch(error => {
// handle error response
console.error(error);
});
}, []);
return (
<div>
<p>"COUCOU LOGIN$@ jeje" </p>
{/* <script src="../script/login42.js"></script> */}
</div>
);
}
export default Login42;

View File

@ -0,0 +1,23 @@
import '../styles/field.css';
// import { useHistory } from 'react-router-dom';
import { useNavigate } from "react-router-dom";
function PlayButton() {
const history = useNavigate();
const handleButtonClick = () => {
let path = `play`;
history(path);
};
return (
<div className="notClicked" id="canvas_container">
<button onClick={handleButtonClick} className="playButton">Play</button>
{/* !buttonClicked && <button onClick={handleButtonClick}>Draw on Canvas</button> */}
</div>
);
}
export default PlayButton;

View File

@ -2,12 +2,13 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import io from 'socket.io-client'; import io from 'socket.io-client';
const socket = io('http://localhost:4000');
// const socket = io('http://192.168.1.14:4000'); // const socket = io('http://192.168.1.14:4000');
// const socket = io('http://86.209.110.20:4000'); // const socket = io('http://86.209.110.20:4000');
// const socket = io('http://172.29.113.91:4000'); // const socket = io('http://172.29.113.91:4000');
export function drawCanvas() { export function drawCanvas() {
const socket = io('http://localhost:4000');
console.log("start function");
const canvas = document.getElementById('myCanvas'); const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
@ -19,6 +20,7 @@ export function drawCanvas() {
//socket //socket
let myId = 0; let myId = 0;
let gameId = 0;
//general canvas //general canvas
const scale = window.devicePixelRatio; const scale = window.devicePixelRatio;
@ -67,12 +69,27 @@ export function drawCanvas() {
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
function matchmaking()
{
console.log(`id ion matcj= ${myId}`)
const info = {
id: myId,
};
socket.emit('pong:matchmaking', info);
}
socket.on('pong:gameId', (data) => {
gameId = data;
});
socket.on('connect', () => { socket.on('connect', () => {
console.log('Connected to NestJS server'); console.log('Connected to NestJS server');
}); });
socket.on('pong:clientId', (data) => { socket.on('pong:clientId', (data) => {
console.log("receive id")
myId = data; myId = data;
console.log(`id is= ${myId}`)
}); });
socket.on('pong:info', (data) => { socket.on('pong:info', (data) => {
@ -86,6 +103,8 @@ export function drawCanvas() {
function send_info() function send_info()
{ {
if (gameId === 0)
return ;
const info = { const info = {
id: myId, id: myId,
width: canvas.width, width: canvas.width,
@ -95,19 +114,24 @@ export function drawCanvas() {
vY: vY, vY: vY,
ballX: ballX, ballX: ballX,
ballY: ballY, ballY: ballY,
gameId: gameId,
}; };
socket.emit('pong:message', info); socket.emit('pong:message', info);
} }
socket.on('pong:paddle', (data) => { socket.on('pong:paddle', (data) => {
console.log("paddle info receive")
oPaddleY = (data.paddleY / data.height) * canvas.height oPaddleY = (data.paddleY / data.height) * canvas.height
}); });
function send_point() function send_point()
{ {
if (gameId === 0)
return ;
console.log("send point"); console.log("send point");
const info = { const info = {
id: myId, id: myId,
gameId: gameId,
point: hisScore, point: hisScore,
} }
socket.emit('pong:point', info); socket.emit('pong:point', info);
@ -129,18 +153,24 @@ export function drawCanvas() {
function send_paddle_info() function send_paddle_info()
{ {
if (gameId === 0)
return ;
const info = { const info = {
id: myId, id: myId,
paddleY: paddleY, paddleY: paddleY,
// width: canvas.width, // width: canvas.width,
height: canvas.height, height: canvas.height,
gameId: gameId,
}; };
socket.emit('pong:paddle', info); socket.emit('pong:paddle', info);
} }
function send_forced_info() function send_forced_info()
{ {
if (gameId === 0)
return ;
const info = { const info = {
gameId: gameId,
width: canvas.width, width: canvas.width,
height: canvas.height, height: canvas.height,
id: myId, id: myId,
@ -200,8 +230,19 @@ export function drawCanvas() {
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
matchmaking();
// while (!gameId)
// ;
function draw(timestamp) function draw(timestamp)
{ {
if (gameId === 0 )
{
requestAnimationFrame(draw)
return;
}
const deltaTime = timestamp - lastUpdateTime; const deltaTime = timestamp - lastUpdateTime;
lastUpdateTime = timestamp; lastUpdateTime = timestamp;

View File

@ -5,39 +5,28 @@ import './styles/index.css';
import App from './components/App'; import App from './components/App';
import Header from './components/Header'; import Header from './components/Header';
import Home from './components/Home'; import Home from './components/Home';
import Login42 from './components/Login42';
import Head from './components/Head'; import Head from './components/Head';
import Field from './components/Field'; import Field from './components/Field';
import PlayButton from './components/PlayButton';
import reportWebVitals from './reportWebVitals'; import reportWebVitals from './reportWebVitals';
import { BrowserRouter, Route, Routes} from 'react-router-dom' import { BrowserRouter, Route, Routes} from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root')); const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( root.render(
<React.StrictMode> <>
{/* <Router>
<Route exact path="/">
<Header />
<Field />
</Route>
<Route exact path="/pong">
<Header />
<Field />
</Route>
</Router> */}
<Head /> <Head />
<Header /> <Header />
<BrowserRouter> <BrowserRouter>
<Routes> <Routes>
<Route exact path="/" element={<Home/>}/> <Route exact path="/" element={<Home/>}/>
{/* <Header /> <Route exact path="/pong" element={<PlayButton />}/>
<Field /> <Route exact path="/pong/play" element={<Field />}/>
</Route> */} <Route exact path="/login42" element={<Login42 />}/>
<Route exact path="/pong" element={<Field />}/> {/* <Route exact path="/chat" element={<Field />}/> */}
{/* <Header />
<Field />
</Route> */}
</Routes> </Routes>
</BrowserRouter>, </BrowserRouter>
</React.StrictMode> </>
); );
// If you want to start measuring performance in your app, pass a function // If you want to start measuring performance in your app, pass a function

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1,7 @@
// function setupLogin()
// {
// // alert("Le bouton a été cliqué !");
// console.log('Hello from login42');
// }
// export default setupLogin;

View File

@ -0,0 +1,155 @@
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap');
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Poppins', sans-serif;
}
.home__container {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.home__container > * {
margin-bottom: 10px;
}
.home__header {
margin-bottom: 30px;
}
.username__input {
padding: 10px;
width: 50%;
}
.home__cta {
width: 200px;
padding: 10px;
font-size: 16px;
cursor: pointer;
background-color: #607eaa;
color: #f9f5eb;
outline: none;
border: none;
border-radius: 5px;
}
.chat {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
}
.chat__sidebar {
height: 100%;
background-color: #f9f5eb;
flex: 0.2;
padding: 20px;
border-right: 1px solid #fdfdfd;
}
.chat__main {
height: 100%;
flex: 0.8;
}
.chat__header {
margin: 30px 0 20px 0;
}
.chat__users > * {
margin-bottom: 10px;
color: #607eaa;
font-size: 14px;
}
.online__users > * {
margin-bottom: 10px;
color: rgb(238, 102, 102);
font-style: italic;
}
.chat__mainHeader {
width: 100%;
height: 10vh;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
background-color: #f9f5eb;
}
.leaveChat__btn {
padding: 10px;
width: 150px;
border: none;
outline: none;
background-color: #d1512d;
cursor: pointer;
color: #eae3d2;
}
.message__container {
width: 100%;
height: 80vh;
background-color: #fff;
padding: 20px;
overflow-y: scroll;
}
.message__container > * {
margin-bottom: 10px;
}
.chat__footer {
padding: 10px;
background-color: #f9f5eb;
height: 10vh;
}
.form {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.message {
width: 80%;
height: 100%;
border-radius: 10px;
border: 1px solid #ddd;
outline: none;
padding: 15px;
}
.sendBtn {
width: 150px;
background-color: green;
padding: 10px;
border: none;
outline: none;
color: #eae3d2;
cursor: pointer;
}
.sendBtn:hover {
background-color: rgb(129, 201, 129);
}
.message__recipient {
background-color: #f5ccc2;
width: 300px;
padding: 10px;
border-radius: 10px;
font-size: 15px;
}
.message__sender {
background-color: rgb(194, 243, 194);
max-width: 300px;
padding: 10px;
border-radius: 10px;
margin-left: auto;
font-size: 15px;
}
.message__chats > p {
font-size: 13px;
}
.sender__name {
text-align: right;
}
.message__status {
position: fixed;
bottom: 50px;
font-size: 13px;
font-style: italic;
}

View File

@ -1,4 +1,19 @@
.field{ .playButton {
background-color: rgb(0, 0, 0);
border-radius: 5vh;
color: white;
display: block;
margin: auto;
margin-top: 30vh;
padding: 2vh 5vw;
height: 10vh;
width: 20vw;
font-size: 300%;
}
.clicked{
/* justify-content: center; */ /* justify-content: center; */
/* display: flex; /* display: flex;
justify-content: center; */ justify-content: center; */

View File

@ -8,6 +8,10 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
private clients: Record<string, Socket> = {}; private clients: Record<string, Socket> = {};
private waitingClients: Set<Socket> = new Set();
// private waitingClients: Set<Socket> = new Set(); // Utilisateurs cherchant un match
private games: Map<string, Socket[]> = new Map(); // Parties en cours, identifiées par un ID
afterInit(server: Server) afterInit(server: Server)
{ {
console.log('PongGateway initialized'); console.log('PongGateway initialized');
@ -17,9 +21,10 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
{ {
console.log(`Client connected: ${client.id}`); console.log(`Client connected: ${client.id}`);
const clientId = uuidv4(); const clientId = client.id;
this.clients[clientId] = client; this.clients[clientId] = client;
client.emit('pong:clientId', clientId); // client.emit('pong:clientId', clientId);
client.emit('pong:clientId', client.id);
console.log(`Total connected clients: ${Object.keys(this.clients).length}`); console.log(`Total connected clients: ${Object.keys(this.clients).length}`);
} }
@ -39,87 +44,175 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
// console.log(`Total connected clients: ${this.clients.size}`); // console.log(`Total connected clients: ${this.clients.size}`);
} }
@SubscribeMessage('pong:matchmaking')
addMatchmaking(client: Socket, payload: any): void
{
console.log("matchmaking");
console.log(payload);
// this.waitingClients.add(client);
this.waitingClients.add(client);
console.log("Adding client to waiting list...");
if (this.waitingClients.size >= 2) {
console.log("Creating new game...");
const players = Array.from(this.waitingClients).slice(0, 2);
players.forEach((player) => {
this.waitingClients.delete(player);
});
const gameId = uuidv4();
this.games.set(gameId, players);
players.forEach((player) => {
player.join(gameId);
console.log(`Player ${player.id} joined game ${gameId}`);
});
players.forEach((player) => {
player.emit('pong:gameId', gameId);
});
}
// console.log(`from: ${client.id}`);
}
// @SubscribeMessage('pong:message')
// handleMessage(client: Socket, payload: any): void
// {
// console.log(`from: ${client.id}`);
// console.log(payload);
// const game = this.games.get(payload.gameId);
// const playersIds = game.map(socket => socket.id);
// // const players = Object.keys(game);
// // if (Object.keys(this.clients).length === 2)
// // {
// // const clientIds = Object.keys(this.clients);
// // console.log(`id of 0= ${clientIds[0]}`);
// // payload.ballX
// // payload.ballY
// // payload.
// if (clientIds[0] === payload.id)
// {
// // console.log("client 0 true");
// if (payload.ballX <= payload.width / 2)
// this.clients[clientIds[1]].emit('pong:info', payload);
// }
// else if (clientIds[1] === payload.id)
// {
// if (payload.ballX < payload.width / 2)
// this.clients[clientIds[0]].emit('pong:info', payload);
// // console.log("client 0 true");
// }
// // }
// console.log("END OF HANDLE");
// }
@SubscribeMessage('pong:message') @SubscribeMessage('pong:message')
handleMessage(client: Socket, payload: any): void handleMessage(client: Socket, payload: any): void
{ {
console.log(`from: ${client.id}`); console.log(`from: ${client.id}`);
console.log(payload); console.log(payload);
if (Object.keys(this.clients).length === 2) const game = this.games.get(payload.gameId);
const playersIds = game.map(socket => socket.id);
if (playersIds[0] === payload.id)
{ {
const clientIds = Object.keys(this.clients);
console.log(`id of 0= ${clientIds[0]}`);
// payload.ballX
// payload.ballY
// payload.
if (clientIds[0] === payload.id)
{
// console.log("client 0 true");
if (payload.ballX <= payload.width / 2) if (payload.ballX <= payload.width / 2)
this.clients[clientIds[1]].emit('pong:info', payload); this.clients[playersIds[1]].emit('pong:info', payload);
} }
else if (clientIds[1] === payload.id) else if (playersIds[1] === payload.id)
{ {
if (payload.ballX < payload.width / 2) if (payload.ballX < payload.width / 2)
this.clients[clientIds[0]].emit('pong:info', payload); this.clients[playersIds[0]].emit('pong:info', payload);
// console.log("client 0 true");
}
} }
console.log("END OF HANDLE"); console.log("END OF HANDLE");
} }
// @SubscribeMessage('pong:forced')
// forcedMessage(client: Socket, payload: any): void
// {
// console.log(`from: ${client.id}`);
// console.log(payload);
// if (Object.keys(this.clients).length === 2)
// {
// const clientIds = Object.keys(this.clients);
// console.log(`id of 0= ${clientIds[0]}`);
// if (clientIds[0] === payload.id)
// {
// this.clients[clientIds[1]].emit('pong:info', payload);
// }
// else if (clientIds[1] === payload.id)
// {
// this.clients[clientIds[0]].emit('pong:info', payload);
// }
// }
// console.log("END OF HANDLE");
// }
@SubscribeMessage('pong:forced') @SubscribeMessage('pong:forced')
forcedMessage(client: Socket, payload: any): void forcedMessage(client: Socket, payload: any): void
{ {
console.log(`from: ${client.id}`); console.log(`from: ${client.id}`);
console.log(payload); console.log(payload);
if (Object.keys(this.clients).length === 2) const game = this.games.get(payload.gameId);
{ const playersIds = game.map(socket => socket.id);
const clientIds = Object.keys(this.clients);
console.log(`id of 0= ${clientIds[0]}`);
// payload.ballX console.log(`id of 0= ${playersIds[0]}`);
// payload.ballY
// payload.
if (clientIds[0] === payload.id) if (playersIds[0] === payload.id)
{ {
// console.log("client 0 true"); this.clients[playersIds[1]].emit('pong:info', payload);
// if (payload.ballX <= payload.width / 2)
this.clients[clientIds[1]].emit('pong:info', payload);
} }
else if (clientIds[1] === payload.id) else if (playersIds[1] === payload.id)
{ {
// if (payload.ballX < payload.width / 2) this.clients[playersIds[0]].emit('pong:info', payload);
this.clients[clientIds[0]].emit('pong:info', payload);
// console.log("client 0 true");
}
} }
console.log("END OF HANDLE"); console.log("END OF HANDLE");
} }
// @SubscribeMessage('pong:paddle')
// handlePaddle(client: Socket, payload: any): void
// {
// console.log(`from: ${client.id}`);
// console.log(payload);
// if (Object.keys(this.clients).length === 2)
// {
// const clientIds = Object.keys(this.clients);
// console.log(`id of 0= ${clientIds[0]}`);
// if (clientIds[0] === payload.id)
// {
// this.clients[clientIds[1]].emit('pong:paddle', payload);
// }
// else if (clientIds[1] === payload.id)
// {
// this.clients[clientIds[0]].emit('pong:paddle', payload);
// }
// }
// console.log("END OF HANDLE");
// }
@SubscribeMessage('pong:paddle') @SubscribeMessage('pong:paddle')
handlePaddle(client: Socket, payload: any): void handlePaddle(client: Socket, payload: any): void
{ {
console.log(`from: ${client.id}`); console.log(`from: ${client.id}`);
console.log(payload); console.log(payload);
if (Object.keys(this.clients).length === 2) const game = this.games.get(payload.gameId);
{ const playersIds = game.map(socket => socket.id);
const clientIds = Object.keys(this.clients);
console.log(`id of 0= ${clientIds[0]}`);
if (clientIds[0] === payload.id) console.log(`id of 0= ${playersIds[0]}`);
if (playersIds[0] === payload.id)
{ {
this.clients[clientIds[1]].emit('pong:paddle', payload); this.clients[playersIds[1]].emit('pong:paddle', payload);
} }
else if (clientIds[1] === payload.id) else if (playersIds[1] === payload.id)
{ {
this.clients[clientIds[0]].emit('pong:paddle', payload); this.clients[playersIds[0]].emit('pong:paddle', payload);
}
} }
console.log("END OF HANDLE"); console.log("END OF HANDLE");
} }
@ -127,19 +220,20 @@ export class PongGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
@SubscribeMessage('pong:point') @SubscribeMessage('pong:point')
handlePoint(client: Socket, payload: any): void handlePoint(client: Socket, payload: any): void
{ {
if (Object.keys(this.clients).length === 2) const game = this.games.get(payload.gameId);
{ const playersIds = game.map(socket => socket.id);
const clientIds = Object.keys(this.clients); console.log(`id of 0= ${playersIds[0]}`);
console.log(`id of 0= ${clientIds[0]}`);
if (clientIds[0] === payload.id) if (playersIds[0] === payload.id)
{ {
this.clients[clientIds[1]].emit('pong:point', payload); this.clients[playersIds[1]].emit('pong:point', payload);
} }
else if (clientIds[1] === payload.id) else if (playersIds[1] === payload.id)
{ {
this.clients[clientIds[0]].emit('pong:point', payload); this.clients[playersIds[0]].emit('pong:point', payload);
} }
} }
}
}
}//end of Web Socket Gateway