Select Git revision
ServerIO.ts
Forked from an inaccessible project.
ServerIO.ts 7.04 KiB
import * as IO from 'socket.io';
import logger from '../logging/WinstonLogger';
import http from 'http';
import Server, {SocketIoInfo} from "../express/Server";
import {UserInfo} from "./UserInfo"
import {Database} from "../database/Database";
import {Question} from "../database/models/Question";
import {response} from "express";
//TODO: In this file you can add/edit all things about socket.io
class ServerIO extends IO.Server {
players: { [key: string]: UserInfo } = {};
playersReady: { [key: string]: boolean }={};
playersScore: { [key: string]: number }={};
nbQuestion!:number;
questions!:Question[];
currentQuestion: Question;
nbGamer=0;
constructor(server: http.Server) {
super(server, {
cors: {
origin: '*'
}
});
this.on('connection', (socket: SocketIoInfo) => {
logger.info(`Nouveau socket vers ${socket.client.conn.remoteAddress}`);
console.log(`Socket info: ${socket.user.username} // ${socket.user.firstname} // ${socket.user.lastname}`);
const playerKey = socket.user.username;
// Vérifiez si le joueur existe déjà dans le dictionnaire
if (this.players[playerKey]) {
// Le joueur est déjà connecté, vous pouvez effectuer une action appropriée ici
console.log(`Player ${playerKey} is already connected.`);
} else {
// Le joueur n'est pas encore connecté, ajoutez-le au dictionnaire
this.players[playerKey] = new UserInfo(
socket.user.username,
socket.user.firstname,
socket.user.lastname
);
this.playersReady[playerKey] = false;
this.playersScore[playerKey] = 0;
this.nbQuestion=0;
console.log(`Player ${playerKey} is connected.`);
}
this.testNumberofPlayer();
this.registerEventsOnSocket(socket);
});
}
private registerEventsOnSocket(socket: SocketIoInfo) {
const playerKey = socket.user.username;
socket.on("player-ready", ()=>{
console.log("nbgamer ready:", this.nbGamer);
if(this.playersReady[playerKey] === true){
console.log(`player ${ playerKey } already ready`)
}else{
logger.info(`player ${playerKey} ready`);
this.nbGamer++;
this.playersReady[playerKey]=true;
this.emit("ready-player", playerKey);
}
this.testNumberOfReady();
});
socket.on("player-not-ready", ()=>{
console.log("nbgamer not ready:", this.nbGamer);
if(this.playersReady[playerKey] === false){
console.log(`player ${ playerKey } already not ready`)
}else{
logger.info(`player ${playerKey} not ready`);
this.nbGamer--;
this.playersReady[playerKey]=false;
this.emit("not-ready-player", playerKey);
}
});
socket.on("on-game", async () => {
if (this.nbGamer === 3) {
let randomQuestion!: any;
if(!this.currentQuestion){
randomQuestion = await this.getRandomQuestion();
}
else{
let question={...this.currentQuestion};
question=question.dataValues as Question;
randomQuestion = question;
}
console.log("send question", randomQuestion);
this.emit("question", randomQuestion);
this.nbQuestion++;
}
});
socket.on("validate-question", async (responseSelected) => {
let randomQuestion = await this.getRandomQuestion();
if (responseSelected === this.currentQuestion.correctResponse) {
// le joueur gagne 1 point
this.playersScore[playerKey]+=1;
}else{
// le joueur perd deux points
this.playersScore[playerKey]-=2;
}
this.nbQuestion++;
if(this.nbQuestion<10){
this.emit("question", randomQuestion);
}else{
const playersScoreFormatted = Object.keys(this.playersScore).reduce((formatted:any, key) => {
formatted[key] = this.playersScore[key];
return formatted;
}, {});
this.emit("game-finished", playersScoreFormatted);
}
})
socket.on('disconnect', () => {
logger.info(`Deconnexion du socket ${ socket.client.conn.remoteAddress }`) ;
console.log(`Socket info: ${ socket.user.username } // ${ socket.user.firstname } // ${socket.user.lastname}`);
const playerKey = socket.user.username;
// Vérifiez si le joueur est dans le dictionnaire
if (this.players[playerKey]) {
// Le joueur est connecté, retirez-le du dictionnaire
delete this.players[playerKey];
delete this.playersReady[playerKey];
console.log(`Player ${playerKey} is disconnected.`);
} else {
// Le joueur n'est pas trouvé dans le dictionnaire, cela peut être un cas anormal
console.log(`Player ${playerKey} is not connected.`);
}
this.testNumberofPlayer();
});
}
private testNumberofPlayer(){
this.emit("players", Object.values(this.players));
if(Object.keys(this.players).length < 3){
this.emit("players-left", 3 - Object.keys(this.players).length)
console.log(Object.keys(this.players).length);
}
if (Object.keys(this.players).length === 3) {
// Démarre le jeu
this.emit('start-game');
}
}
// Méthode pour récupérer une question aléatoire
async getRandomQuestion() {
if (!this.questions || this.questions.length === 0) {
this.questions = await Database.getAllQuestions();
this.questions.forEach(q => {
q.possibleResponse = JSON.parse(q.possibleResponse);
q.correctResponse = parseInt(String(q.correctResponse));
});
}
const randomIndex = Math.floor(Math.random() * this.questions.length);
this.currentQuestion = this.questions[randomIndex];
this.questions.splice(randomIndex, 1);
// pour ne pas envoyer au frontend la reponse attendue
let randomQuestion={...this.currentQuestion};
randomQuestion=randomQuestion.dataValues as Question;
return randomQuestion;
}
private testNumberOfReady() {
let allPlayerReady = true;
Object.values(this.playersReady).forEach(playerReady => {
if (!playerReady) {
allPlayerReady = false;
}
});
if (allPlayerReady) {
this.emit("game-ready-start");
}
}
}
export default ServerIO;