chore(eslint/format): remformatted all files and fixed eslint issues

This commit is contained in:
Maieul BOYER 2026-01-02 14:49:59 +01:00 committed by Maix0
parent 945a36dcc1
commit a4b3cc3c4b
6 changed files with 213 additions and 152 deletions

View file

@ -10,12 +10,8 @@ import { broadcast } from './broadcast';
import type { ClientProfil, ClientMessage } from './chat_types'; import type { ClientProfil, ClientMessage } from './chat_types';
import { sendInvite } from './sendInvite'; import { sendInvite } from './sendInvite';
import { setGameLink } from './setGameLink'; import { setGameLink } from './setGameLink';
import { emit } from 'process';
import { Boolean, Record } from 'typebox/type';
import { UserId } from '@shared/database/mixin/user'; import { UserId } from '@shared/database/mixin/user';
// colors for console.log // colors for console.log
export const color = { export const color = {
red: '\x1b[31m', red: '\x1b[31m',
@ -30,8 +26,8 @@ declare const __SERVICE_NAME: string;
// Global map of clients // Global map of clients
// key = socket, value = clientname // key = socket, value = clientname
interface ClientInfo { interface ClientInfo {
user: string; user: string;
lastSeen: number; lastSeen: number;
} }
export const clientChat = new Map<string, ClientInfo>(); export const clientChat = new Map<string, ClientInfo>();
@ -76,45 +72,61 @@ declare module 'fastify' {
io: Server<{ io: Server<{
inviteGame: (data: ClientProfil) => void; inviteGame: (data: ClientProfil) => void;
message: (msg: string) => void; message: (msg: string) => void;
batmove_Left: (direction: "up" | "down") => void; batmove_Left: (direction: 'up' | 'down') => void;
batmove_Right: (direction: "up" | "down") => void; batmove_Right: (direction: 'up' | 'down') => void;
batLeft_update: (y:number) => void; batLeft_update: (y: number) => void;
batRight_update: (y:number) => void; batRight_update: (y: number) => void;
ballPos_update: (x:number, y:number) => void; ballPos_update: (x: number, y: number) => void;
MsgObjectServer: (data: { message: ClientMessage }) => void; MsgObjectServer: (data: { message: ClientMessage }) => void;
queuJoin: (userID : UserId) => void; queuJoin: (userID: UserId) => void;
}>; }>;
} }
} }
function isInRange(x : number, low : number, high : number) { function isInRange(x: number, low: number, high: number) {
if (x >= low && x <= high) if (x >= low && x <= high) return true;
return (true); return false;
return (false);
} }
async function sendScore(socket : Socket, scoreLeft : number, scoreRight : number) { // idk why, sometimes... it fails? async function sendScore(
let msg : ClientMessage = {destination : "score-info", command: "", user:"", text:scoreLeft.toString() + ":" + scoreRight.toString(), SenderWindowID:""}; socket: Socket,
scoreLeft: number,
scoreRight: number,
) {
// idk why, sometimes... it fails?
const msg: ClientMessage = {
destination: 'score-info',
command: '',
user: '',
text: scoreLeft.toString() + ':' + scoreRight.toString(),
SenderWindowID: '',
};
socket.emit('MsgObjectServer', {message : msg}); socket.emit('MsgObjectServer', { message: msg });
} }
async function onReady(fastify: FastifyInstance) { async function onReady(fastify: FastifyInstance) {
// shows address for connection au server transcendance // shows address for connection au server transcendance
const session = process.env.SESSION_MANAGER ?? ''; const session = process.env.SESSION_MANAGER ?? '';
if (session) { if (session) {
const part = session.split('/')[1]; const part = session.split('/')[1];
const machineName = part.split('.')[0]; const machineName = part.split('.')[0];
console.log(color.yellow, 'Connect at : https://' + machineName + ':8888/app/login'); console.log(
color.yellow,
'Connect at : https://' + machineName + ':8888/app/login',
);
} }
// DRAW AREA // DRAW AREA
const TOP_EDGE = 0; // top edge of the field // top edge of the field
const BOTTOM_EDGE = 450; // bottom edge of the field; const TOP_EDGE = 0;
// bottom edge of the field;
const BOTTOM_EDGE = 450;
const LEFT_EDGE = 0; const LEFT_EDGE = 0;
const RIGHT_EDGE = 800; const RIGHT_EDGE = 800;
void LEFT_EDGE;
// PADDLEs // PADDLEs
const PADDLE_HEIGHT = 80; const PADDLE_HEIGHT = 80;
const PADDLE_WIDTH = 12; const PADDLE_WIDTH = 12;
@ -122,20 +134,25 @@ async function onReady(fastify: FastifyInstance) {
const PADDLE_SPEED = 20; const PADDLE_SPEED = 20;
const PADDLE_X_OFFSET = 4; const PADDLE_X_OFFSET = 4;
const MAX_PADDLE_Y = BOTTOM_EDGE - PADDLE_HEIGHT; // 370 // 370
const PADDLE_START = BOTTOM_EDGE / 2 - PADDLE_HEIGHT / 2; // 185 const MAX_PADDLE_Y = BOTTOM_EDGE - PADDLE_HEIGHT;
// 185
const PADDLE_START = BOTTOM_EDGE / 2 - PADDLE_HEIGHT / 2;
// BALL // BALL
const BALL_SIZE = 8 * 2 + 4; // widht times 2 bc rounded on moth sides + 4 for border // widht times 2 bc rounded on moth sides + 4 for border
const START_BALLX = (RIGHT_EDGE / 2) - BALL_SIZE; const BALL_SIZE = 8 * 2 + 4;
const START_BALLY = (BOTTOM_EDGE / 2) - BALL_SIZE; const START_BALLX = RIGHT_EDGE / 2 - BALL_SIZE;
const START_BALLY = BOTTOM_EDGE / 2 - BALL_SIZE;
const ACCELERATION_FACTOR = 1.15; const ACCELERATION_FACTOR = 1.15;
const ABS_MAX_BALL_SPEED = 3; const ABS_MAX_BALL_SPEED = 3;
// val inits // val inits
let paddleLeft = PADDLE_START; //shared start bat position // shared start bat position
let paddleRight = PADDLE_START; //shared start bat position let paddleLeft = PADDLE_START;
// shared start bat position
let paddleRight = PADDLE_START;
let ballPosX = START_BALLX; let ballPosX = START_BALLX;
let ballPosY = START_BALLY; let ballPosY = START_BALLY;
@ -144,123 +161,174 @@ async function onReady(fastify: FastifyInstance) {
let scoreL = 0; let scoreL = 0;
let scoreR = 0; let scoreR = 0;
// uuid, game uid - if not in game empty string
let games : Record<UserId, string> = {}; // uuid, game uid - if not in game empty string const games: Record<UserId, string> = {};
fastify.io.on('connection', (socket: Socket) => { fastify.io.on('connection', (socket: Socket) => {
socket.emit("batLeft_update", paddleLeft); socket.emit('batLeft_update', paddleLeft);
socket.emit("batRight_update", paddleRight); socket.emit('batRight_update', paddleRight);
socket.emit("ballPos_update", ballPosX, ballPosY); socket.emit('ballPos_update', ballPosX, ballPosY);
sendScore(socket, scoreL, scoreR); sendScore(socket, scoreL, scoreR);
// GAME // GAME
// paddle handling // paddle handling
socket.on('batmove_Left', (direction: "up" | "down") => { socket.on('batmove_Left', (direction: 'up' | 'down') => {
if (direction === "up") { if (direction === 'up') {
paddleLeft -= PADDLE_SPEED; paddleLeft -= PADDLE_SPEED;
} }
if (direction === "down") { if (direction === 'down') {
paddleLeft += PADDLE_SPEED; paddleLeft += PADDLE_SPEED;
} }
// position of bat leftplokoplpl // position of bat leftplokoplpl
paddleLeft = Math.max(TOP_EDGE, Math.min(MAX_PADDLE_Y, paddleLeft)); paddleLeft = Math.max(TOP_EDGE, Math.min(MAX_PADDLE_Y, paddleLeft));
console.log("batLeft_update:", paddleLeft); console.log('batLeft_update:', paddleLeft);
socket.emit("batLeft_update", paddleLeft); socket.emit('batLeft_update', paddleLeft);
}); });
socket.on('batmove_Right', (direction: "up" | "down") => { socket.on('batmove_Right', (direction: 'up' | 'down') => {
if (direction === "up") { if (direction === 'up') {
paddleRight -= PADDLE_SPEED; paddleRight -= PADDLE_SPEED;
} }
if (direction === "down") { if (direction === 'down') {
paddleRight += PADDLE_SPEED; paddleRight += PADDLE_SPEED;
} }
// position of bat left // position of bat left
paddleRight = Math.max(TOP_EDGE, Math.min(MAX_PADDLE_Y, paddleRight)); paddleRight = Math.max(
socket.emit("batRight_update", paddleRight); TOP_EDGE,
}); Math.min(MAX_PADDLE_Y, paddleRight),
// ball handling: );
setInterval(async () => { socket.emit('batRight_update', paddleRight);
const new_ballPosX = ballPosX + ballSpeedX; });
const new_ballPosY = ballPosY + ballSpeedY; // ball handling:
setInterval(async () => {
const new_ballPosX = ballPosX + ballSpeedX;
const new_ballPosY = ballPosY + ballSpeedY;
if (((isInRange(new_ballPosY, paddleLeft, paddleLeft + PADDLE_HEIGHT) || isInRange(new_ballPosY + BALL_SIZE *2, paddleLeft, paddleLeft + PADDLE_HEIGHT)) // y ok ? if (
&& isInRange(new_ballPosX, PADDLE_X_OFFSET, PADDLE_X_OFFSET + PADDLE_WIDTH) && ballSpeedX < 0) || // x ok? && ball going toward paddle? ((isInRange(
((isInRange(new_ballPosY, paddleRight, paddleRight + PADDLE_HEIGHT) || isInRange(new_ballPosY + BALL_SIZE *2, paddleRight, paddleRight + PADDLE_HEIGHT)) // right side equations new_ballPosY,
&& isInRange(new_ballPosX + BALL_SIZE * 2, RIGHT_EDGE - PADDLE_X_OFFSET - PADDLE_WIDTH, RIGHT_EDGE - PADDLE_X_OFFSET)) && ballSpeedX > 0) paddleLeft,
{ paddleLeft + PADDLE_HEIGHT,
ballSpeedX *= -1; ) ||
ballSpeedX *= ACCELERATION_FACTOR; isInRange(
ballSpeedY *= ACCELERATION_FACTOR; new_ballPosY + BALL_SIZE * 2,
console.log('bat colision'); paddleLeft,
} paddleLeft + PADDLE_HEIGHT,
else if (new_ballPosX < 0 || new_ballPosX + BALL_SIZE*2 > RIGHT_EDGE) { )) &&
ballPosX = START_BALLX; // y ok ?
ballPosY = START_BALLY; isInRange(
ballSpeedX = (Math.random() - .5) < 0 ? -1 : 1; new_ballPosX,
PADDLE_X_OFFSET,
PADDLE_X_OFFSET + PADDLE_WIDTH,
) &&
ballSpeedX < 0) ||
// x ok? && ball going toward paddle?
((isInRange(
new_ballPosY,
paddleRight,
paddleRight + PADDLE_HEIGHT,
) ||
isInRange(
new_ballPosY + BALL_SIZE * 2,
paddleRight,
paddleRight + PADDLE_HEIGHT,
)) &&
// right side equations
isInRange(
new_ballPosX + BALL_SIZE * 2,
RIGHT_EDGE - PADDLE_X_OFFSET - PADDLE_WIDTH,
RIGHT_EDGE - PADDLE_X_OFFSET,
) &&
ballSpeedX > 0)
) {
ballSpeedX *= -1;
ballSpeedX *= ACCELERATION_FACTOR;
ballSpeedY *= ACCELERATION_FACTOR;
console.log('bat colision');
}
else if (
new_ballPosX < 0 ||
new_ballPosX + BALL_SIZE * 2 > RIGHT_EDGE
) {
ballPosX = START_BALLX;
ballPosY = START_BALLY;
ballSpeedX = Math.random() - 0.5 < 0 ? -1 : 1;
if (new_ballPosX < 0) { if (new_ballPosX < 0) {
scoreR += 1; scoreR += 1;
ballSpeedY = -1; ballSpeedY = -1;
} else {
scoreL += 1;
ballSpeedY = 1;
}
if (scoreL >= 5 || scoreR >= 5)
{
console.log('game should stop + board reset');
ballSpeedX = 0; // temp solution
ballSpeedY = 0;
// reset board :D
}
console.log('point scored');
sendScore(socket, scoreL, scoreR);
// TODO: score point + ball reset + spd reset
} }
else if (new_ballPosY < 0 || new_ballPosY + BALL_SIZE*2 > BOTTOM_EDGE) { else {
ballSpeedY *= -1; scoreL += 1;
ballSpeedX *= ACCELERATION_FACTOR; ballSpeedY = 1;
ballSpeedY *= ACCELERATION_FACTOR;
} }
ballSpeedX = Math.max(-ABS_MAX_BALL_SPEED, Math.min(ballSpeedX, ABS_MAX_BALL_SPEED)); if (scoreL >= 5 || scoreR >= 5) {
ballSpeedY = Math.max(-ABS_MAX_BALL_SPEED, Math.min(ballSpeedY, ABS_MAX_BALL_SPEED)); console.log('game should stop + board reset');
// temp solution
ballSpeedX = 0;
ballSpeedY = 0;
// reset board :D
}
console.log('point scored');
sendScore(socket, scoreL, scoreR);
// TODO: score point + ball reset + spd reset
}
else if (
new_ballPosY < 0 ||
new_ballPosY + BALL_SIZE * 2 > BOTTOM_EDGE
) {
ballSpeedY *= -1;
ballSpeedX *= ACCELERATION_FACTOR;
ballSpeedY *= ACCELERATION_FACTOR;
}
ballSpeedX = Math.max(
-ABS_MAX_BALL_SPEED,
Math.min(ballSpeedX, ABS_MAX_BALL_SPEED),
);
ballSpeedY = Math.max(
-ABS_MAX_BALL_SPEED,
Math.min(ballSpeedY, ABS_MAX_BALL_SPEED),
);
ballPosX += ballSpeedX; ballPosX += ballSpeedX;
ballPosY += ballSpeedY; ballPosY += ballSpeedY;
socket.emit("ballPos_update", ballPosX, ballPosY); socket.emit('ballPos_update', ballPosX, ballPosY);
}, 16) }, 16);
// QUEUE HANDL // QUEUE HANDL
socket.on('queuJoin', async (uuid: UserId) => { socket.on('queuJoin', async (uuid: UserId) => {
console.log('queu join recieved for : ', uuid); console.log('queu join recieved for : ', uuid);
if (!games.hasOwnProperty(uuid)) { if (!(uuid in games.hasOwnProperty)) {
console.log("new user in game search queu"); console.log('new user in game search queu');
games[uuid] = ""; games[uuid] = '';
} else if (games.hasOwnProperty(uuid) && games[uuid] == "") { }
console.log('already searching for game'); else if (uuid in games && games[uuid] == '') {
} else { // (games.hasOwnProperty(uuid) && games[uuid] != "") { console.log('already searching for game');
console.log('user alredy in game'); }
return ; else {
} // (games.hasOwnProperty(uuid) && games[uuid] != "") {
// TODO: step2 : sesrch in record<> find guid w/ "" &/ pair them up console.log('user alredy in game');
// TODO: step3 : move game logic to lifecycle of queu'ed game return;
}) }
// TODO: step2 : sesrch in record<> find guid w/ "" &/ pair them up
// TODO: step3 : move game logic to lifecycle of queu'ed game
});
// other: // other:
socket.on('message', (message: string) => { socket.on('message', (message: string) => {
const obj: ClientMessage = JSON.parse(message) as ClientMessage; const obj: ClientMessage = JSON.parse(message) as ClientMessage;
clientChat.set(socket.id, { user: obj.user, lastSeen: Date.now() }); clientChat.set(socket.id, { user: obj.user, lastSeen: Date.now() });
socket.emit('welcome', {msg: 'Welcome to the chat! : '}); socket.emit('welcome', { msg: 'Welcome to the chat! : ' });
broadcast(fastify, obj, obj.SenderWindowID); broadcast(fastify, obj, obj.SenderWindowID);
}); });
socket.on('inviteGame', async (data: string) => { socket.on('inviteGame', async (data: string) => {
const clientName: string = clientChat.get(socket.id)?.user || ''; const clientName: string = clientChat.get(socket.id)?.user || '';
const profilInvite: ClientProfil = JSON.parse(data) || ''; const profilInvite: ClientProfil = JSON.parse(data) || '';
const inviteHtml: string = 'invites you to a game ' + setGameLink(''); const inviteHtml: string =
'invites you to a game ' + setGameLink('');
if (clientName !== null) { if (clientName !== null) {
sendInvite(fastify, inviteHtml, profilInvite); sendInvite(fastify, inviteHtml, profilInvite);
} }
}); });
}); });
} }

View file

@ -3,20 +3,20 @@ import { clientChat, color } from './app';
import { FastifyInstance } from 'fastify'; import { FastifyInstance } from 'fastify';
export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender?: string) { export function broadcast(fastify: FastifyInstance, data: ClientMessage, sender?: string) {
fastify.io.fetchSockets().then((sockets) => { fastify.io.fetchSockets().then((sockets) => {
for (const socket of sockets) { for (const socket of sockets) {
// Skip sender's own socket // Skip sender's own socket
if (socket.id === sender) continue; if (socket.id === sender) continue;
// Get client name from map // Get client name from map
const clientInfo = clientChat.get(socket.id); const clientInfo = clientChat.get(socket.id);
if (!clientInfo?.user) { if (!clientInfo?.user) {
console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`); console.log(color.yellow, `Skipping socket ${socket.id} (no user found)`);
continue; continue;
} }
// Emit structured JSON object // Emit structured JSON object
socket.emit('MsgObjectServer', { message: data }); socket.emit('MsgObjectServer', { message: data });
// Debug logs // Debug logs
// console.log(color.green, `'DEBUG LOG: Broadcast to:', ${data.command} message: ${data.text}`); // console.log(color.green, `'DEBUG LOG: Broadcast to:', ${data.command} message: ${data.text}`);
} }
}); });
} }

View file

@ -9,15 +9,15 @@ export type ClientMessage = {
export type ClientProfil = { export type ClientProfil = {
command: string, command: string,
destination: string, destination: string,
type: string, type: string,
user: string, user: string,
loginName: string, loginName: string,
userID: string, userID: string,
text: string, text: string,
timestamp: number, timestamp: number,
SenderWindowID:string, SenderWindowID: string,
SenderName: string, SenderName: string,
Sendertext: string, Sendertext: string,
innerHtml?: string, innerHtml?: string,
}; };

View file

@ -2,15 +2,12 @@ import { FastifyPluginAsync } from 'fastify';
import { Static, Type } from 'typebox'; import { Static, Type } from 'typebox';
import { broadcast } from '../broadcast'; import { broadcast } from '../broadcast';
export const PongReq = Type.Object({ export const PongReq = Type.Object({
message: Type.String(), message: Type.String(),
}); });
export type PongReq = Static<typeof PongReq>; export type PongReq = Static<typeof PongReq>;
const route: FastifyPluginAsync = async (fastify): Promise<void> => { const route: FastifyPluginAsync = async (fastify): Promise<void> => {
fastify.post<{ Body: PongReq }>( fastify.post<{ Body: PongReq }>(
'/api/pong/broadcast', '/api/pong/broadcast',
@ -38,9 +35,6 @@ export default route;
* send message info to the fronatend via the route '/api/pong/broadcast' * send message info to the fronatend via the route '/api/pong/broadcast'
*/ */
// const route: FastifyPluginAsync = async (fastify): Promise<void> => { // const route: FastifyPluginAsync = async (fastify): Promise<void> => {
// fastify.post('/api/chat/broadcast', { // fastify.post('/api/chat/broadcast', {
// schema: { // schema: {

View file

@ -1,4 +1,3 @@
export function setGameLink(link: string): string { export function setGameLink(link: string): string {
if (!link) { if (!link) {
link = '<a href=\'https://google.com\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>Click me</a>'; link = '<a href=\'https://google.com\' style=\'color: blue; text-decoration: underline; cursor: pointer;\'>Click me</a>';