diff --git a/.gitignore b/.gitignore index 253262c..78ad554 100644 --- a/.gitignore +++ b/.gitignore @@ -45,4 +45,8 @@ sketch ### modules ### yarn.lock -package-lock.json \ No newline at end of file +package-lock.json + +# db + +socialgraph.db diff --git a/cryptide_project/src/Components/GraphContainer.tsx b/cryptide_project/src/Components/GraphContainer.tsx index 8eb67c5..10bc725 100644 --- a/cryptide_project/src/Components/GraphContainer.tsx +++ b/cryptide_project/src/Components/GraphContainer.tsx @@ -13,7 +13,6 @@ import Bot from "../model/Bot"; import NodePerson from "../model/Graph/NodePerson"; import { useAuth } from "../Contexts/AuthContext"; - interface MyGraphComponentProps { onNodeClick: (shouldShowChoiceBar: boolean) => void; handleShowTurnBar: (shouldShowTurnBar: boolean) => void @@ -23,6 +22,7 @@ interface MyGraphComponentProps { changecptTour: (newcptTour : number) => void addToHistory: (message : string) => void solo : boolean + isDaily : boolean setNetwork: (network: Network) => void showLast: boolean } @@ -39,18 +39,43 @@ let lastSocketId= "" let firstLap = true let cptHistory = 0 let lastNodes: NodePerson[] = [] +let cptEndgame = 0 +let firstEnigme = true +let endgame= false + +const MyGraphComponent: React.FC = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, isDaily, addToHistory, showLast, setNetwork}) => { + let cptTour: number = 0 -const MyGraphComponent: React.FC = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, addToHistory, showLast, setNetwork}) => { -let cptTour: number = 0 + //* Gestion du temps : + let initMtn = 0 - const {isLoggedIn, user} = useAuth() - const { indices, indice, person, personNetwork, setNodeIdData, players, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData } = useGame(); + const {isLoggedIn, user, manager} = useAuth(); + const { indices, indice, person, personNetwork, setNodeIdData, players, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData, dailyEnigme, setNbCoupData, settempsData} = useGame(); const params = new URLSearchParams(window.location.search); const navigate = useNavigate(); const [lastIndex, setLastIndex] = useState(-1) + const [elapsedTime, setElapsedTime] = useState(0); + + useEffect(() => { + // Démarrez le timer au montage du composant + const intervalId = setInterval(() => { + setElapsedTime((prevElapsedTime) => prevElapsedTime + 0.5); + settempsData(elapsedTime) + + // Vérifiez si la durée est écoulée, puis arrêtez le timer + if (endgame) { + clearInterval(intervalId); + } + }, 500); + + // Nettoyez l'intervalle lorsque le composant est démonté + return () => clearInterval(intervalId); + }, [elapsedTime, endgame]); + + useEffect(() =>{ touchedPlayer=playerTouched if (touchedPlayer == -1){ @@ -195,7 +220,7 @@ let cptTour: number = 0 if (first){ first = false - + endgame= false if (!solo){ for(let i = 0; i { + pairs.forEach((pair) => { + const i = indices.findIndex((indice) => pair.first.getId() === indice.getId()) + const node = networkData.nodes.get().find((n) => index == n.id) + if (node != undefined){ + networkData.nodes.update({id: node.id, label: node.label + positionToEmoji(i, pair.second)}) + const test = networkData.nodes.get().find((n) => index == n.id) + } + }) + }); + } + socket.on("reset graph", () => { console.log("reset graph") initialOptions.physics.enabled = true @@ -286,7 +324,6 @@ let cptTour: number = 0 }) socket.on("node checked",(id, works, askedIndex, newPlayerIndex, socketId) => { - console.log(newPlayerIndex) const node = nodes.get().find((n) => id == n.id) if (node!=undefined){ onNodeClick(false) @@ -448,49 +485,65 @@ let cptTour: number = 0 }) socket.on("end game", (winnerIndex) =>{ - const currentPlayer = players[actualPlayerIndex]; - const winner = players[winnerIndex]; - - setNodeIdData(-1) - setActualPlayerIndexData(-1) - setLastIndex(-1) - setPlayerTouched(-1) - setWinnerData(players[winnerIndex]) - - if(isLoggedIn){ - if(solo){ - - } - else{ - if(winner.id === currentPlayer.id){ - console.log("Vous avez gagné !"); - } - else{ - console.log("Vous avez perdu !"); + if (cptEndgame % 2 == 0){ + cptEndgame++; + const currentPlayer = players[actualPlayerIndex]; + const winner = players[winnerIndex]; + + setNodeIdData(-1) + setActualPlayerIndexData(-1) + setLastIndex(-1) + setPlayerTouched(-1) + setWinnerData(players[winnerIndex]) + setElapsedTime(0) + + first = true + cptHistory = 0 + askedWrong=false + askedWrongBot=false + endgame = true + + try{ + if(isLoggedIn){ + if(!solo){ + if(user && user.onlineStats){ + // console.log("nbGames: " + user.onlineStats.nbGames + " nbWins: " + user.onlineStats.nbWins); + if(winner.id === currentPlayer.id){ + // Ajouter une victoire + user.onlineStats.nbWins = null ? user.onlineStats.nbWins = 1 : user.onlineStats.nbWins += 1; + } + // Update les stats + user.onlineStats.nbGames = null ? user.onlineStats.nbGames = 1 : user.onlineStats.nbGames += 1; + user.onlineStats.ratio = user.onlineStats.nbWins / user.onlineStats.nbGames; + + manager.userService.updateOnlineStats(user.pseudo, user.onlineStats.nbGames, user.onlineStats.nbWins, user.onlineStats.ratio); + } + else{ + console.error("User not found"); + } + } } } + catch(e){ + console.log(e); + } + finally{ + socket.off("end game") + socket.off("asked all") + socket.off("opacity activated") + socket.off("opacity deactivated") + socket.off("reset graph") + socket.off("node checked") + socket.off("already asked") + socket.off("asked wrong") + socket.off("asked") + socket.off("put correct background") + socket.off("put grey background") + socket.off("put imossible grey") + + navigate("/endgame") + } } - - first = true - cptHistory = 0 - askedWrong=false - askedWrongBot=false - - - socket.off("end game") - socket.off("asked all") - socket.off("opacity activated") - socket.off("opacity deactivated") - socket.off("reset graph") - socket.off("node checked") - socket.off("already asked") - socket.off("asked wrong") - socket.off("asked") - socket.off("put correct background") - socket.off("put grey background") - socket.off("put imossible grey") - - navigate("/endgame") }) @@ -505,7 +558,7 @@ let cptTour: number = 0 } if (a==indices.length){ //networkData.nodes.update({id: p.getId(), label: p.getName() + "\n🔵"}) - console.log(p) + //console.log(p) } }); @@ -644,7 +697,31 @@ let cptTour: number = 0 works = false } if (index == indices.length - 1 && works){ - navigate("/endgame") + + if (user!=null){ + setWinnerData(user) + } + cptTour ++; + setNbCoupData(cptTour) + setElapsedTime(0) + endgame = true + + try{ + if(user && user.soloStats){ + user.soloStats.nbGames = null ? user.soloStats.nbGames = 1 : user.soloStats.nbGames += 1; + if(cptTour < user.soloStats.bestScore || user.soloStats.bestScore == 0 || user.soloStats.bestScore == null){ + user.soloStats.bestScore = cptTour; + } + user.soloStats.avgNbTry = (user.soloStats.avgNbTry * (user.soloStats.nbGames - 1) + cptTour) / user.soloStats.nbGames; + + manager.userService.updateSoloStats(user.pseudo, user.soloStats.nbGames, user.soloStats.bestScore, user.soloStats.avgNbTry); + } + } + catch(error){ + console.log(error); + } + + navigate("/endgame?solo=true&daily=" + isDaily) } } @@ -653,7 +730,6 @@ let cptTour: number = 0 } addToHistory(person.getName() + " n'est pas le tueur !"); //TODO préciser le nombre d'indice qu'il a de juste - //TODO METTRE LA WIN CONDITION ICI AVEC LE MERGE cptTour ++; // On Incrémente le nombre de tour du joueur const tour = cptTour+1; addToHistory("<----- [Tour " + tour +"/"+networkData.nodes.length + "] ----->"); diff --git a/cryptide_project/src/Contexts/GameContext.tsx b/cryptide_project/src/Contexts/GameContext.tsx index 32da9d2..e6f7b8f 100644 --- a/cryptide_project/src/Contexts/GameContext.tsx +++ b/cryptide_project/src/Contexts/GameContext.tsx @@ -1,5 +1,6 @@ import React, { createContext, useContext, useState, ReactNode } from 'react'; import Indice from '../model/Indices/Indice'; +import Pair from '../model/Pair'; import Person from '../model/Person'; import PersonNetwork from '../model/PersonsNetwork'; import Player from '../model/Player'; @@ -17,6 +18,9 @@ interface GameContextProps { room: string; onlyFalse: boolean winner: Player | null + dailyEnigme: Map[]> + nbCoup : number + temps : number setIndicesData: (newIndices: Indice[]) => void; setIndiceData: (newIndice: Indice) => void; setPersonData: (newPerson: Person) => void; @@ -30,6 +34,9 @@ interface GameContextProps { setOnlyFalseData: (newOnlyFalse: boolean) => void setWinnerData: (winner: Player) => void reset: () => void + setDailyEnigmeData: (map: Map[]>) => void + setNbCoupData: (newNbCoup : number) => void + settempsData: (newtemps : number) => void } const GameContext = createContext(undefined); @@ -51,6 +58,9 @@ export const GameProvider: React.FC = ({ children }) => { const [room, setRoom] = useState("") const [onlyFalse, setOnlyFalse] = useState(false) const [winner, setWinner] = useState(null) + const [dailyEnigme, setDailyEnigme] = useState[]>>(new Map()) + const [nbCoup, setNbCoup] = useState(0); + const [temps, settemps] = useState(0); const setIndicesData = (newIndices: Indice[]) => { @@ -102,6 +112,19 @@ export const GameProvider: React.FC = ({ children }) => { setWinner(winner) } + const setDailyEnigmeData = (map: Map[]>) => { + setDailyEnigme(map) + } + + + const setNbCoupData = (newNbCoup : number) => { + setNbCoup(newNbCoup); + } + + const settempsData = (newtemps : number) => { + settemps(newtemps); + } + const reset = () => { setIndices([]) setActualPlayerIndex(-1) @@ -114,10 +137,12 @@ export const GameProvider: React.FC = ({ children }) => { setTurnPlayerIndex(-1) setNodeId(-1) setIndice(null) + setNbCoup(0) + settemps(0) } return ( - + {children} ); diff --git a/cryptide_project/src/Pages/EndGame.css b/cryptide_project/src/Pages/EndGame.css index 9af5187..2cb9654 100644 --- a/cryptide_project/src/Pages/EndGame.css +++ b/cryptide_project/src/Pages/EndGame.css @@ -79,4 +79,39 @@ margin: 0 15px 0 15px; padding: 10px; box-shadow: 5px 5px 5px rgb(246, 246, 246); +} + +.SoloContainer{ + display: flex; + flex-direction: column; + align-items: center; + + border: solid 1px whitesmoke; + border-radius: 15px; + background-color: white; + + max-width: 50%; +} + +.indicesolo{ + display: flex; + flex-wrap: wrap; + justify-content: space-evenly; + + /* margin: 10px 0; */ + /* max-height: 200px; */ +} + +.solostat{ + display: flex; + justify-content: space-between; + width: 70%; +} + +.solostat p { + border: solid 1px whitesmoke; + border-radius: 15px; + background-color: white; + + padding: 10px; } \ No newline at end of file diff --git a/cryptide_project/src/Pages/EndGame.tsx b/cryptide_project/src/Pages/EndGame.tsx index d588183..2e56dee 100644 --- a/cryptide_project/src/Pages/EndGame.tsx +++ b/cryptide_project/src/Pages/EndGame.tsx @@ -22,62 +22,125 @@ import { Link } from 'react-router-dom'; /* lang */ import { FormattedMessage } from 'react-intl'; import { useGame } from '../Contexts/GameContext'; +import { map } from 'lodash'; +import Player from '../model/Player'; function EndGame() { + const params = new URLSearchParams(window.location.search); + + //* Gestion solo + let IsSolo: boolean = false + const solotmp = params.get('solo'); + if (solotmp == "true"){ + IsSolo=true + } + + + //* Gestion daily + let IsDaily: boolean = false + const dailytmp = params.get('daily'); + if (dailytmp == "true"){ + IsDaily=true + } + const {reset} = useGame() const resetAll = () => { reset() } - - const {winner, person, players, indices} =useGame() - console.log(winner) + + const {winner, person, players, indices, nbCoup, temps} =useGame() + let indice = indices[0] - const index = players.findIndex((p) => p.id == winner?.id) - if (index != -1) { - indice = indices[index] - } + let losingPlayers : Player[]; + if(!IsSolo){ + const index = players.findIndex((p) => p.id == winner?.id) + if (index != -1) { + indice = indices[index] + } + - let losingPlayers; - if (winner != null) { - losingPlayers = players.filter(player => player.id !== winner.id); - } else { - losingPlayers = players; + if (winner != null) { + losingPlayers = players.filter(player => player.id !== winner.id); + } else { + losingPlayers = players; + } + } + else{ + losingPlayers = []; } - const theme = useTheme(); return (
+ {!IsSolo && +
+
+
+

{winner?.pseudo} a gagné !

+

Le tueur était {person?.getName()}

+
+
+
+ +

{indices[players.findIndex((p) => p.id == winner?.id)].ToString("fr")}

+
+
+
+ +
+
+ {losingPlayers.map((player, index) => ( +
+ {player.id !== winner?.id && ( +
+ {}} index={index} showCircle={false}/> +
{indices[players.findIndex((p) => p.id == player?.id)].ToString("fr")}
+
+ )} +
+ ))} +
+
+ +
+
+
+ }
-
-

{winner?.pseudo} a gagné !

-

Le tueur était {person?.getName()}

-
+
+

Vous avez gagné !

+

Le tueur était {person?.getName()}

+
-

{indices[players.findIndex((p) => p.id == winner?.id)].ToString("fr")}

+

{winner?.pseudo}

+
-
- {losingPlayers.map((player, index) => ( -
- {player.id !== winner?.id && ( -
- {}} index={index} showCircle={false}/> -
{indices[players.findIndex((p) => p.id == player?.id)].ToString("fr")}
-
- )} -
- ))} +
+
+ {!IsDaily &&

Nombre de coups : {nbCoup}

} +

Temps : {temps}s

+
+
+ {indices.map((indice, index) => ( + //
+
+
Indice {index+1} : {indice.ToString("fr")}
+
+ //
+ )) + } +
diff --git a/cryptide_project/src/Pages/InGame.tsx b/cryptide_project/src/Pages/InGame.tsx index 7c04d6e..e3feff6 100644 --- a/cryptide_project/src/Pages/InGame.tsx +++ b/cryptide_project/src/Pages/InGame.tsx @@ -62,6 +62,13 @@ const InGame = ({locale, changeLocale}) => { IsSolo=false } + //* Gestion daily + let isDaily: boolean = true + const isDailytmp = params.get('daily'); + if (isDailytmp == "false"){ + isDaily=false + } + //* Historique const [history, setHistory] = useState([]); const [showLast, setShowLast] = useState(false) @@ -212,6 +219,7 @@ const InGame = ({locale, changeLocale}) => { changecptTour={changecptTour} addToHistory={addToHistory} solo={IsSolo} + isDaily={isDaily} setPlayerTouched={handleSetPlayerTouched} playerTouched={playerTouched} setNetwork={setNetworkData} @@ -219,7 +227,7 @@ const InGame = ({locale, changeLocale}) => {
- {IsSolo && + {IsSolo && !isDaily &&
{
} - -
- {history.map((item, index) => ( -
{item}
- ))} -
+ {!isDaily && +
+ {history.map((item, index) => ( +
{item}
+ ))} +
+ }
*/} - {!IsSolo && + {!IsSolo && + } - {IsSolo && + {IsSolo && + + }
diff --git a/cryptide_project/src/Pages/Lobby.tsx b/cryptide_project/src/Pages/Lobby.tsx index 176879c..2ad4ce3 100644 --- a/cryptide_project/src/Pages/Lobby.tsx +++ b/cryptide_project/src/Pages/Lobby.tsx @@ -209,7 +209,7 @@ function Lobby() {
diff --git a/cryptide_project/src/Pages/Play.tsx b/cryptide_project/src/Pages/Play.tsx index 4f4030f..03c5ddf 100644 --- a/cryptide_project/src/Pages/Play.tsx +++ b/cryptide_project/src/Pages/Play.tsx @@ -8,8 +8,7 @@ import './Play.css'; import { useTheme } from '../Style/ThemeContext'; /* Component */ -import ButtonImgNav from "../Components/ButtonImgNav" -import SessionService from "../services/SessionService"; +import ButtonImgNav from "../Components/ButtonImgNav"; /* Img */ /* Icon */ @@ -23,12 +22,63 @@ import defaultImg from "../res/img/Person.png" /* Types */ import User from '../model/User'; +import EnigmeDuJourCreator from '../model/EnigmeDuJourCreator'; +import Stub from '../model/Stub'; + +import SessionService from '../services/SessionService'; import { loadImageAsync } from '../ImageHelper'; function Play() { + let first = true + const theme=useTheme() const {isLoggedIn, login, user, setUserData, manager } = useAuth(); - + const {setDailyEnigmeData} = useGame() + + useEffect(() => { + const fetchUserInformation = async () => { + try { + const sessionData = await SessionService.getSession(); + + // Vérifie si il y a une session + if (sessionData.user) { + // Il y a une session on récupère les infos du joueur + const updatedPlayer: User = new User(socket.id, sessionData.user.pseudo, sessionData.user.profilePicture, { + nbGames: sessionData.user.soloStats.nbGames, + bestScore: sessionData.user.soloStats.bestScore, + avgNbTry: sessionData.user.soloStats.avgNbTry, + }, + { + nbGames: sessionData.user.onlineStats.nbGames, + nbWins: sessionData.user.onlineStats.nbWins, + ratio: sessionData.user.onlineStats.ratio, + }) + login(); + setUserData(updatedPlayer); + } else { + // Pas de session on génère un guest random + const guestPlayer: User = new User(socket.id, 'Guest_' + Math.floor(Math.random() * 1000000), '', + { + nbGames: 0, + bestScore: 0, + avgNbTry: 0, + }, + { + nbGames: 0, + nbWins: 0, + ratio: 0, + }) + setUserData(guestPlayer); + } + } catch (error) { + console.error(error); + } + }; + + fetchUserInformation(); + }, [isLoggedIn]); + + const { setIndicesData, setPersonData, setPersonNetworkData } = useGame(); @@ -69,10 +119,24 @@ function Play() { setPersonNetworkData(networkPerson) setIndicesData(choosenIndices) setIndicesData(choosenIndices) - navigate('/game?solo=true'); + navigate('/game?solo=true&daily=false'); } + function launchEngimeJour(){ + const [networkPerson, choosenPerson, choosenIndices] = GameCreator.CreateGame(3, 30) + setPersonData(choosenPerson) + setPersonNetworkData(networkPerson) + setIndicesData(choosenIndices) + setIndicesData(choosenIndices) + if (first){ + first = false + const map = EnigmeDuJourCreator.createEnigme(networkPerson, choosenIndices, choosenPerson, Stub.GenerateIndice()) + setDailyEnigmeData(map) + } + navigate('/game?solo=true&daily=true'); + } + useEffect(() => { const handleLobbyCreated = (newRoom: any) => { @@ -118,6 +182,7 @@ function Play() {
+ diff --git a/cryptide_project/src/SocketConfig.ts b/cryptide_project/src/SocketConfig.ts index 54015d8..4db4397 100644 --- a/cryptide_project/src/SocketConfig.ts +++ b/cryptide_project/src/SocketConfig.ts @@ -1,6 +1,5 @@ import { io } from "socket.io-client"; -import {ADRESSE_WEBSERVER} from "./AdressConfig" - +import { ADRESSE_WEBSERVER } from "./AdressConfig"; const socket = io(ADRESSE_WEBSERVER); diff --git a/cryptide_project/src/Translations/fr.json b/cryptide_project/src/Translations/fr.json index e9cf193..5b37344 100644 --- a/cryptide_project/src/Translations/fr.json +++ b/cryptide_project/src/Translations/fr.json @@ -55,7 +55,7 @@ "color_start": "Le suspect a les cheveux", "color_end": "", - "nb_friends_indice_start": "Le suspect", + "nb_friends_indice_start": "Le suspect a", "nb_friends_indice_end": "amis", "nb_sports_indice_start": "Le suspect pratique", diff --git a/cryptide_project/src/adressConfig.ts b/cryptide_project/src/adressConfig.ts new file mode 100644 index 0000000..8d49e11 --- /dev/null +++ b/cryptide_project/src/adressConfig.ts @@ -0,0 +1,7 @@ +const ADRESSE_WEBSERVER = "http://localhost:3002" + +const ADRESSE_DBSERVER = "http://localhost:3003" + +const ADRESSE_WEBSITE = "http://localhost:3000" + +export {ADRESSE_DBSERVER, ADRESSE_WEBSERVER, ADRESSE_WEBSITE} \ No newline at end of file diff --git a/cryptide_project/src/model/DataManagers/DbUserService.ts b/cryptide_project/src/model/DataManagers/DbUserService.ts index 49dded6..8454966 100644 --- a/cryptide_project/src/model/DataManagers/DbUserService.ts +++ b/cryptide_project/src/model/DataManagers/DbUserService.ts @@ -44,6 +44,31 @@ class DbUserService implements IUserService{ } } + async updateSoloStats(pseudo: string, nbGames: number, bestScore: number, avgNbTry: number): Promise { + try { + const result = await SessionService.updateSoloStats(pseudo, nbGames, bestScore, avgNbTry); + if (result) { + console.log("Stats solo updated"); + } else { + console.log("Stats solo not updated"); + } + } catch (error) { + console.error(error); + } + } + + async updateOnlineStats(pseudo: string, nbGames: number, bestScore: number, ratio: number): Promise { + try { + const result = await SessionService.updateOnlineStats(pseudo, nbGames, bestScore, ratio); + if (result) { + console.log("Stats online updated"); + } else { + console.log("Stats online not updated"); + } + } catch (error) { + console.error(error); + } + } } export default DbUserService \ No newline at end of file diff --git a/cryptide_project/src/model/DataManagers/IUserService.ts b/cryptide_project/src/model/DataManagers/IUserService.ts index 5eb0f43..dafc349 100644 --- a/cryptide_project/src/model/DataManagers/IUserService.ts +++ b/cryptide_project/src/model/DataManagers/IUserService.ts @@ -1,8 +1,9 @@ import User from "../User"; interface IUserService{ - fetchUserInformation(): Promise<[User | null, boolean]> + updateSoloStats(pseudo: string, nbGames: number, bestScore: number, avgNbTry: number): Promise + updateOnlineStats(pseudo: string, nbGames: number, bestScore: number, ratio: number): Promise } diff --git a/cryptide_project/src/model/EnigmeDuJourCreator.ts b/cryptide_project/src/model/EnigmeDuJourCreator.ts new file mode 100644 index 0000000..126c3bb --- /dev/null +++ b/cryptide_project/src/model/EnigmeDuJourCreator.ts @@ -0,0 +1,74 @@ +import IndiceTesterFactory from "./Factory/IndiceTesterFactory"; +import Indice from "./Indices/Indice"; +import Pair from "./Pair"; +import Person from "./Person"; +import PersonNetwork from "./PersonsNetwork"; + +class EnigmeDuJourCreator{ + + + static createEnigme(personNetwork: PersonNetwork, choosenIndices: Indice[], choosenPerson: Person, allIndices: Indice[]): Map[]>{ + const map = new Map[]>() + personNetwork.getPersons().forEach((p) =>{ + map.set(p.getId(), []) + }) + + console.log("START ENIGME") + + choosenIndices.forEach((choosenIndice) => { + const choosenIndiceTester = IndiceTesterFactory.Create(choosenIndice) + const modifiedPersons: Pair[] = [] + let possibleIndices: Indice[] = [...allIndices] + + let i = 0 + + while (possibleIndices.length != 1){ + let tmpPossibleIndices: Indice[] = [...possibleIndices] + let choosenPair : Pair = new Pair(personNetwork.getPersons()[0], true) + for(const person of personNetwork.getPersons().filter((p) => p.getId() !== choosenPerson.getId())){ + const veryTmpIndice = [...possibleIndices] + if (!choosenIndiceTester.Works(person)){ + possibleIndices.forEach((possibleIndice, index) =>{ + const tester = IndiceTesterFactory.Create(possibleIndice) + if (tester.Works(person)){ + const t = veryTmpIndice.findIndex((tmpIndice) => tmpIndice.getId() == possibleIndice.getId()) + if (t != -1){ + veryTmpIndice.splice(t, 1) + } + } + }) + if (veryTmpIndice.length{ + const tester = IndiceTesterFactory.Create(possibleIndice) + if (!tester.Works(person)){ + const t = veryTmpIndice.findIndex((tmpIndice) => tmpIndice.getId() == possibleIndice.getId()) + if (t != -1){ + veryTmpIndice.splice(t, 1) + } + } + }) + if (veryTmpIndice.length " + choosenIndice.ToString("fr")) + console.log("possibleIndices => " + possibleIndices[0].ToString("fr")) + modifiedPersons.forEach((pair) =>{ + map.get(pair.first.getId())?.push(new Pair(choosenIndice, pair.second)) + }) + }) + return map + } +} +export default EnigmeDuJourCreator \ No newline at end of file diff --git a/cryptide_project/src/model/Indices/NbSportIndice.ts b/cryptide_project/src/model/Indices/NbSportIndice.ts index eab219e..9d3bcb2 100644 --- a/cryptide_project/src/model/Indices/NbSportIndice.ts +++ b/cryptide_project/src/model/Indices/NbSportIndice.ts @@ -16,7 +16,7 @@ class NbSportIndice extends Indice { // Implémentation de la méthode abstraite ToString(lang: string): string { let json = GetJsonFile(lang) - let string = `${json.nb_sports_indice_start}`; + let string = `${json.nb_sports_indice_start} `; this.nbSport.forEach((i, index) =>{ if (index == this.nbSport.length - 1){ string += i diff --git a/cryptide_project/src/model/Indices/SportIndice.ts b/cryptide_project/src/model/Indices/SportIndice.ts index 2dbae4b..ecd9ea5 100644 --- a/cryptide_project/src/model/Indices/SportIndice.ts +++ b/cryptide_project/src/model/Indices/SportIndice.ts @@ -16,10 +16,10 @@ class SportIndice extends Indice { let string = json.sport_start; for (let i = 0; i { if (err) { console.error(err); res.status(500).json({ error: 'Erreur lors de la déconnexion.' }); } else { + console.log("[" + hour + ":" + minutes + "] " + pseudo + " have been disconnected."); res.status(200).json({ message: 'Déconnexion réussie' }); } }); diff --git a/cryptide_project/src/server/controllers/SessionController.js b/cryptide_project/src/server/controllers/SessionController.js index 7b40331..0b8f646 100644 --- a/cryptide_project/src/server/controllers/SessionController.js +++ b/cryptide_project/src/server/controllers/SessionController.js @@ -3,6 +3,9 @@ const DatabaseService = require('../services/DatabaseService'); class SessionController { static async getUserInformation(req, res) { const db = new DatabaseService(); + const date = new Date(); + const hour = date.getHours(); + const minutes = date.getMinutes(); try{ await db.connect(); @@ -15,8 +18,7 @@ class SessionController { req.session.user.soloStats = await db.getSoloStatsByUserId(req.session.user.idUser); req.session.user.onlineStats = await db.getOnlineStatsByUserId(req.session.user.idUser); - console.log(req.session.user); - + console.log("[" + hour + ":" + minutes + "] " + req.session.user.pseudo + " have a session."); res.status(200).json({ user: req.session.user }); } catch(error){ @@ -28,6 +30,88 @@ class SessionController { } } + static async updateSoloStats(req, res) { + const db = new DatabaseService(); + const date = new Date(); + const hour = date.getHours(); + const minutes = date.getMinutes(); + + try{ + await db.connect(); + + const user = await db.getUserByPseudo(req.body.pseudo); + + if (!user) { + res.status(200).json({ error: "true", message: 'User not found' }); + return; + } + + const soloStats = await db.getSoloStatsByUserId(user.idUser); + + if (!soloStats) { + res.status(200).json({ error: "true", message: 'Solo stats not found' }); + return; + } + + await db.updateSoloStats(user.idUser, req.body.nbGames, req.body.bestScore, req.body.avgNbTry); + + const newSoloStats = await db.getSoloStatsByUserId(user.idUser); + + req.session.user.soloStats = newSoloStats; + + console.log("[" + hour + ":" + minutes + "] " + req.session.user.pseudo + "'s solot_stats are updated."); + res.status(200).json({ user: req.session.user }); + } + catch(error){ + console.error(error); + res.status(500).json({ error: 'Erreur lors de la mise à jour des statistiques solo.' }); + } + finally{ + await db.disconnect(); + } + } + + static async updateOnlineStats(req, res) { + const db = new DatabaseService(); + const date = new Date(); + const hour = date.getHours(); + const minutes = date.getMinutes(); + + try{ + await db.connect(); + + const user = await db.getUserByPseudo(req.body.pseudo); + + if (!user) { + res.status(200).json({ error: "true", message: 'User not found' }); + return; + } + + const onlineStats = await db.getOnlineStatsByUserId(user.idUser); + + if (!onlineStats) { + res.status(200).json({ error: "true", message: 'Online stats not found' }); + return; + } + + await db.updateOnlineStats(user.idUser, req.body.nbGames, req.body.nbWins, req.body.ratio); + + const newOnlineStats = await db.getOnlineStatsByUserId(user.idUser); + + req.session.user.onlineStats = newOnlineStats; + + console.log("[" + hour + ":" + minutes + "] " + req.session.user.pseudo + "'s online_stats are updated."); + res.status(200).json({ user: req.session.user }); + } + catch(error){ + console.error(error); + res.status(500).json({ error: 'Erreur lors de la mise à jour des statistiques en ligne.' }); + } + finally{ + await db.disconnect(); + } + } + static async UpdatePseudo(req, res){ const db = new DatabaseService(); diff --git a/cryptide_project/src/server/routes/AuthRoutes.js b/cryptide_project/src/server/routes/AuthRoutes.js index a0da069..63fb965 100644 --- a/cryptide_project/src/server/routes/AuthRoutes.js +++ b/cryptide_project/src/server/routes/AuthRoutes.js @@ -12,5 +12,7 @@ router.delete('/auth/delAccount', AuthController.delAccount) // Routes pour les sessions router.get('/session', SessionController.getUserInformation); router.put('/session/updatePseudo', SessionController.UpdatePseudo); +router.put('/session/updateSoloStats', SessionController.updateSoloStats); +router.put('/session/updateOnlineStats', SessionController.updateOnlineStats); module.exports = router; diff --git a/cryptide_project/src/server/server.js b/cryptide_project/src/server/server.js index e47f470..889f8cd 100644 --- a/cryptide_project/src/server/server.js +++ b/cryptide_project/src/server/server.js @@ -6,13 +6,14 @@ const crypto = require('crypto'); const authRoutes = require('./routes/authRoutes'); const DatabaseService = require('./services/DatabaseService'); + const app = express(); const port = 3003; // Middleware app.use(cors( { - origin: ['http://localhost:3000', "http://172.20.10.4:3000"], + origin: ["http://localhost:3000", "http://172.20.10.4:3000"], credentials: true } )); // Autoriser les requêtes cross-origin diff --git a/cryptide_project/src/server/services/DatabaseService.js b/cryptide_project/src/server/services/DatabaseService.js index 3888a87..d465c7d 100644 --- a/cryptide_project/src/server/services/DatabaseService.js +++ b/cryptide_project/src/server/services/DatabaseService.js @@ -51,6 +51,20 @@ class DatabaseService { }); } + // Récupère l'utilisateur par son id + async getUserByID(id){ + return new Promise((resolve, reject) => { + this.client.get('SELECT * FROM users WHERE idUser = ?', id, (err, result) => { + if(err){ + reject(err); + } + else{ + resolve(result); + } + }); + }); + } + // Récupère stats solo de l'utilisateur async getSoloStatsByUserId(userId){ return new Promise((resolve, reject) => { @@ -107,6 +121,33 @@ class DatabaseService { }); } + // Mettre à jour les stats solo de l'utilisateur + async updateSoloStats(userId, nbGames, bestScore, avgNbTry){ + return new Promise((resolve, reject) => { + this.client.run('UPDATE solo_stats SET nbGames = ?, bestScore = ?, avgNbTry = ? WHERE idUser = ?', [nbGames, bestScore, avgNbTry, userId], (err, result) => { + if(err){ + reject(err); + } + else{ + resolve(result); + } + }); + }); + } + + // Mettre à jour les stats online de l'utilisateur + async updateOnlineStats(userId, nbGames, nbWins, ratio){ + return new Promise((resolve, reject) => { + this.client.run('UPDATE online_stats SET nbGames = ?, nbWins = ?, ratio = ? WHERE idUser = ?', [nbGames, nbWins, ratio, userId], (err, result) => { + if(err){ + reject(err); + } + else{ + resolve(result); + } + }); + }); + } async initSoloStats(userId) { return new Promise((resolve, reject) => { diff --git a/cryptide_project/src/services/AuthService.tsx b/cryptide_project/src/services/AuthService.tsx index 638788f..7ec366d 100644 --- a/cryptide_project/src/services/AuthService.tsx +++ b/cryptide_project/src/services/AuthService.tsx @@ -1,3 +1,4 @@ +import { ADRESSE_DBSERVER } from '../adressConfig'; import VerificationService from './VerificationService'; import {ADRESSE_DBSERVER} from "../AdressConfig" import User from '../model/User'; diff --git a/cryptide_project/src/services/SessionService.tsx b/cryptide_project/src/services/SessionService.tsx index d75bfab..230f236 100644 --- a/cryptide_project/src/services/SessionService.tsx +++ b/cryptide_project/src/services/SessionService.tsx @@ -24,6 +24,66 @@ class SessionService { } } + static async updateSoloStats(pseudo: string, nbGames: number, bestScore: number, avgNbTry: number){ + try { + const response = await fetch(ADRESSE_DBSERVER + '/session/updateSoloStats', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', + body: JSON.stringify({ + pseudo, + nbGames, + bestScore, + avgNbTry + }), + }); + + if (response.ok) { + const result = await response.json(); + return result; + } else { + const errorResponse = await response.json(); + throw new Error(errorResponse.error); + } + } catch (error) { + console.error(error); + throw error; + } + } + + static async updateOnlineStats(pseudo: string, nbGames: number, nbWins: number, ratio: number){ + try { + + console.log("updateOnlineStats : ", pseudo, nbGames, nbWins, ratio); + const response = await fetch(ADRESSE_DBSERVER + '/session/updateOnlineStats', { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + }, + credentials: 'include', + body: JSON.stringify({ + pseudo, + nbGames, + nbWins, + ratio + }), + }); + + if (response.ok) { + const result = await response.json(); + return result; + } else { + const errorResponse = await response.json(); + throw new Error(errorResponse.error); + } + } catch (error) { + console.error(error); + throw error; + } + } + static async UpdatePseudo(pseudo : string, newPseudo : string) { console.log("pseudo : " + pseudo + " newpseudo : " + newPseudo) try {