pull/83/head
Pierre Ferreira 1 year ago
commit c75f397c66

4
.gitignore vendored

@ -46,3 +46,7 @@ sketch
### modules ### ### modules ###
yarn.lock yarn.lock
package-lock.json package-lock.json
# db
socialgraph.db

@ -13,7 +13,6 @@ import Bot from "../model/Bot";
import NodePerson from "../model/Graph/NodePerson"; import NodePerson from "../model/Graph/NodePerson";
import { useAuth } from "../Contexts/AuthContext"; import { useAuth } from "../Contexts/AuthContext";
interface MyGraphComponentProps { interface MyGraphComponentProps {
onNodeClick: (shouldShowChoiceBar: boolean) => void; onNodeClick: (shouldShowChoiceBar: boolean) => void;
handleShowTurnBar: (shouldShowTurnBar: boolean) => void handleShowTurnBar: (shouldShowTurnBar: boolean) => void
@ -23,6 +22,7 @@ interface MyGraphComponentProps {
changecptTour: (newcptTour : number) => void changecptTour: (newcptTour : number) => void
addToHistory: (message : string) => void addToHistory: (message : string) => void
solo : boolean solo : boolean
isDaily : boolean
setNetwork: (network: Network) => void setNetwork: (network: Network) => void
showLast: boolean showLast: boolean
} }
@ -39,18 +39,43 @@ let lastSocketId= ""
let firstLap = true let firstLap = true
let cptHistory = 0 let cptHistory = 0
let lastNodes: NodePerson[] = [] let lastNodes: NodePerson[] = []
let cptEndgame = 0
let firstEnigme = true
let endgame= false
const MyGraphComponent: React.FC<MyGraphComponentProps> = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, isDaily, addToHistory, showLast, setNetwork}) => {
let cptTour: number = 0
const MyGraphComponent: React.FC<MyGraphComponentProps> = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, addToHistory, showLast, setNetwork}) => { //* Gestion du temps :
let cptTour: number = 0 let initMtn = 0
const {isLoggedIn, user} = useAuth() const {isLoggedIn, user, manager} = useAuth();
const { indices, indice, person, personNetwork, setNodeIdData, players, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData } = useGame(); 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 params = new URLSearchParams(window.location.search);
const navigate = useNavigate(); const navigate = useNavigate();
const [lastIndex, setLastIndex] = useState(-1) 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(() =>{ useEffect(() =>{
touchedPlayer=playerTouched touchedPlayer=playerTouched
if (touchedPlayer == -1){ if (touchedPlayer == -1){
@ -195,7 +220,7 @@ let cptTour: number = 0
if (first){ if (first){
first = false first = false
endgame= false
if (!solo){ if (!solo){
for(let i = 0; i<indices.length; i++){ for(let i = 0; i<indices.length; i++){
mapIndexPersons.set(i, []) mapIndexPersons.set(i, [])
@ -257,6 +282,19 @@ let cptTour: number = 0
setNetwork(network) setNetwork(network)
if (isDaily){
dailyEnigme.forEach((pairs, index) => {
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", () => { socket.on("reset graph", () => {
console.log("reset graph") console.log("reset graph")
initialOptions.physics.enabled = true initialOptions.physics.enabled = true
@ -286,7 +324,6 @@ let cptTour: number = 0
}) })
socket.on("node checked",(id, works, askedIndex, newPlayerIndex, socketId) => { socket.on("node checked",(id, works, askedIndex, newPlayerIndex, socketId) => {
console.log(newPlayerIndex)
const node = nodes.get().find((n) => id == n.id) const node = nodes.get().find((n) => id == n.id)
if (node!=undefined){ if (node!=undefined){
onNodeClick(false) onNodeClick(false)
@ -448,6 +485,8 @@ let cptTour: number = 0
}) })
socket.on("end game", (winnerIndex) =>{ socket.on("end game", (winnerIndex) =>{
if (cptEndgame % 2 == 0){
cptEndgame++;
const currentPlayer = players[actualPlayerIndex]; const currentPlayer = players[actualPlayerIndex];
const winner = players[winnerIndex]; const winner = players[winnerIndex];
@ -456,27 +495,39 @@ let cptTour: number = 0
setLastIndex(-1) setLastIndex(-1)
setPlayerTouched(-1) setPlayerTouched(-1)
setWinnerData(players[winnerIndex]) setWinnerData(players[winnerIndex])
setElapsedTime(0)
first = true
cptHistory = 0
askedWrong=false
askedWrongBot=false
endgame = true
try{
if(isLoggedIn){ if(isLoggedIn){
if(solo){ 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{ else{
if(winner.id === currentPlayer.id){ console.error("User not found");
console.log("Vous avez gagné !");
} }
else{
console.log("Vous avez perdu !");
} }
} }
} }
catch(e){
first = true console.log(e);
cptHistory = 0 }
askedWrong=false finally{
askedWrongBot=false
socket.off("end game") socket.off("end game")
socket.off("asked all") socket.off("asked all")
socket.off("opacity activated") socket.off("opacity activated")
@ -491,6 +542,8 @@ let cptTour: number = 0
socket.off("put imossible grey") socket.off("put imossible grey")
navigate("/endgame") navigate("/endgame")
}
}
}) })
@ -505,7 +558,7 @@ let cptTour: number = 0
} }
if (a==indices.length){ if (a==indices.length){
//networkData.nodes.update({id: p.getId(), label: p.getName() + "\n🔵"}) //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 works = false
} }
if (index == indices.length - 1 && works){ 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 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 cptTour ++; // On Incrémente le nombre de tour du joueur
const tour = cptTour+1; const tour = cptTour+1;
addToHistory("<----- [Tour " + tour +"/"+networkData.nodes.length + "] ----->"); addToHistory("<----- [Tour " + tour +"/"+networkData.nodes.length + "] ----->");

@ -1,5 +1,6 @@
import React, { createContext, useContext, useState, ReactNode } from 'react'; import React, { createContext, useContext, useState, ReactNode } from 'react';
import Indice from '../model/Indices/Indice'; import Indice from '../model/Indices/Indice';
import Pair from '../model/Pair';
import Person from '../model/Person'; import Person from '../model/Person';
import PersonNetwork from '../model/PersonsNetwork'; import PersonNetwork from '../model/PersonsNetwork';
import Player from '../model/Player'; import Player from '../model/Player';
@ -17,6 +18,9 @@ interface GameContextProps {
room: string; room: string;
onlyFalse: boolean onlyFalse: boolean
winner: Player | null winner: Player | null
dailyEnigme: Map<number, Pair<Indice, boolean>[]>
nbCoup : number
temps : number
setIndicesData: (newIndices: Indice[]) => void; setIndicesData: (newIndices: Indice[]) => void;
setIndiceData: (newIndice: Indice) => void; setIndiceData: (newIndice: Indice) => void;
setPersonData: (newPerson: Person) => void; setPersonData: (newPerson: Person) => void;
@ -30,6 +34,9 @@ interface GameContextProps {
setOnlyFalseData: (newOnlyFalse: boolean) => void setOnlyFalseData: (newOnlyFalse: boolean) => void
setWinnerData: (winner: Player) => void setWinnerData: (winner: Player) => void
reset: () => void reset: () => void
setDailyEnigmeData: (map: Map<number, Pair<Indice, boolean>[]>) => void
setNbCoupData: (newNbCoup : number) => void
settempsData: (newtemps : number) => void
} }
const GameContext = createContext<GameContextProps | undefined>(undefined); const GameContext = createContext<GameContextProps | undefined>(undefined);
@ -51,6 +58,9 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
const [room, setRoom] = useState<string>("") const [room, setRoom] = useState<string>("")
const [onlyFalse, setOnlyFalse] = useState<boolean>(false) const [onlyFalse, setOnlyFalse] = useState<boolean>(false)
const [winner, setWinner] = useState<Player | null>(null) const [winner, setWinner] = useState<Player | null>(null)
const [dailyEnigme, setDailyEnigme] = useState<Map<number, Pair<Indice, boolean>[]>>(new Map())
const [nbCoup, setNbCoup] = useState<number>(0);
const [temps, settemps] = useState<number>(0);
const setIndicesData = (newIndices: Indice[]) => { const setIndicesData = (newIndices: Indice[]) => {
@ -102,6 +112,19 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
setWinner(winner) setWinner(winner)
} }
const setDailyEnigmeData = (map: Map<number, Pair<Indice, boolean>[]>) => {
setDailyEnigme(map)
}
const setNbCoupData = (newNbCoup : number) => {
setNbCoup(newNbCoup);
}
const settempsData = (newtemps : number) => {
settemps(newtemps);
}
const reset = () => { const reset = () => {
setIndices([]) setIndices([])
setActualPlayerIndex(-1) setActualPlayerIndex(-1)
@ -114,10 +137,12 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
setTurnPlayerIndex(-1) setTurnPlayerIndex(-1)
setNodeId(-1) setNodeId(-1)
setIndice(null) setIndice(null)
setNbCoup(0)
settemps(0)
} }
return ( return (
<GameContext.Provider value={{ indices, setIndicesData, indice, setIndiceData, person, setPersonData, personNetwork, setPersonNetworkData, players, setPlayersData, nodeId, setNodeIdData, askedPersons, setAskedPersonsData, actualPlayerIndex, setActualPlayerIndexData, turnPlayerIndex, setTurnPlayerIndexData, room, setRoomData, onlyFalse, setOnlyFalseData, winner, setWinnerData, reset }}> <GameContext.Provider value={{ indices, setIndicesData, indice, setIndiceData, person, setPersonData, personNetwork, setPersonNetworkData, players, setPlayersData, nodeId, setNodeIdData, askedPersons, setAskedPersonsData, actualPlayerIndex, setActualPlayerIndexData, turnPlayerIndex, setTurnPlayerIndexData, room, setRoomData, onlyFalse, setOnlyFalseData, winner, setWinnerData, reset, dailyEnigme, setDailyEnigmeData, nbCoup, setNbCoupData, temps, settempsData}}>
{children} {children}
</GameContext.Provider> </GameContext.Provider>
); );

@ -80,3 +80,38 @@
padding: 10px; padding: 10px;
box-shadow: 5px 5px 5px rgb(246, 246, 246); 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;
}

@ -22,36 +22,62 @@ import { Link } from 'react-router-dom';
/* lang */ /* lang */
import { FormattedMessage } from 'react-intl'; import { FormattedMessage } from 'react-intl';
import { useGame } from '../Contexts/GameContext'; import { useGame } from '../Contexts/GameContext';
import { map } from 'lodash';
import Player from '../model/Player';
function EndGame() { 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 {reset} = useGame()
const resetAll = () => { const resetAll = () => {
reset() reset()
} }
const {winner, person, players, indices} =useGame() const {winner, person, players, indices, nbCoup, temps} =useGame()
console.log(winner)
let indice = indices[0] let indice = indices[0]
let losingPlayers : Player[];
if(!IsSolo){
const index = players.findIndex((p) => p.id == winner?.id) const index = players.findIndex((p) => p.id == winner?.id)
if (index != -1) { if (index != -1) {
indice = indices[index] indice = indices[index]
} }
let losingPlayers;
if (winner != null) { if (winner != null) {
losingPlayers = players.filter(player => player.id !== winner.id); losingPlayers = players.filter(player => player.id !== winner.id);
} else { } else {
losingPlayers = players; losingPlayers = players;
} }
}
else{
losingPlayers = [];
}
const theme = useTheme(); const theme = useTheme();
return ( return (
<div>
{!IsSolo &&
<div> <div>
<div className="head"> <div className="head">
<header className='leaderboard-header' style={{ borderColor: theme.colors.primary }}> <header className='leaderboard-header' style={{ borderColor: theme.colors.primary }}>
@ -84,6 +110,43 @@ function EndGame() {
</div> </div>
</div> </div>
</div> </div>
}
<div className="head">
<header className='leaderboard-header' style={{ borderColor: theme.colors.primary }}>
<h1>Vous avez gagné !</h1>
<h3>Le tueur était <u>{person?.getName()}</u></h3>
</header>
</div>
<div className='winner'>
<img src={Person} width='250' height='250'/>
<h1>{winner?.pseudo}</h1>
</div>
<div className='bottom'>
<div className='centerDivH' onClick={resetAll}>
<BigButtonNav dest="/play" img={Leave}/>
</div>
<div className="SoloContainer">
<div className='solostat'>
{!IsDaily && <p>Nombre de coups : {nbCoup}</p> }
<p>Temps : {temps}s</p>
</div>
<div className='indicesolo'>
{indices.map((indice, index) => (
// <div className="playerContainer" key={index}>
<div>
<h6 className='indiceDisplay'> <u>Indice {index+1}</u> : {indice.ToString("fr")}</h6>
</div>
//</div>
))
}
</div>
</div>
<div className='centerDivH'>
<BigButtonNav dest="/lobby" img={Replay}/>
</div>
</div>
</div>
); );
} }

@ -62,6 +62,13 @@ const InGame = ({locale, changeLocale}) => {
IsSolo=false IsSolo=false
} }
//* Gestion daily
let isDaily: boolean = true
const isDailytmp = params.get('daily');
if (isDailytmp == "false"){
isDaily=false
}
//* Historique //* Historique
const [history, setHistory] = useState<string[]>([]); const [history, setHistory] = useState<string[]>([]);
const [showLast, setShowLast] = useState(false) const [showLast, setShowLast] = useState(false)
@ -212,6 +219,7 @@ const InGame = ({locale, changeLocale}) => {
changecptTour={changecptTour} changecptTour={changecptTour}
addToHistory={addToHistory} addToHistory={addToHistory}
solo={IsSolo} solo={IsSolo}
isDaily={isDaily}
setPlayerTouched={handleSetPlayerTouched} setPlayerTouched={handleSetPlayerTouched}
playerTouched={playerTouched} playerTouched={playerTouched}
setNetwork={setNetworkData} setNetwork={setNetworkData}
@ -219,7 +227,7 @@ const InGame = ({locale, changeLocale}) => {
</div> </div>
{IsSolo && {IsSolo && !isDaily &&
<div className='nbLaps' style={{ <div className='nbLaps' style={{
backgroundColor: theme.colors.primary, backgroundColor: theme.colors.primary,
borderColor: theme.colors.secondary borderColor: theme.colors.secondary
@ -228,12 +236,13 @@ const InGame = ({locale, changeLocale}) => {
</div> </div>
} }
{!isDaily &&
<div className='historique' id="history-container"> <div className='historique' id="history-container">
{history.map((item, index) => ( {history.map((item, index) => (
<div key={index}>{item}</div> <div key={index}>{item}</div>
))} ))}
</div> </div>
}
<div className='paramDiv'> <div className='paramDiv'>
<button className='button' <button className='button'
@ -289,7 +298,8 @@ const InGame = ({locale, changeLocale}) => {
<img src={Check} alt="check" height="40"/> <img src={Check} alt="check" height="40"/>
</button> */} </button> */}
{!IsSolo && <Link to='/info' target='_blank'> {!IsSolo &&
<Link to='/info' target='_blank'>
<button className='button' <button className='button'
style={{ style={{
backgroundColor: theme.colors.tertiary, backgroundColor: theme.colors.tertiary,
@ -315,7 +325,9 @@ const InGame = ({locale, changeLocale}) => {
<img src={ eye } alt="indice" height="40"/> <img src={ eye } alt="indice" height="40"/>
</button>} </button>}
{IsSolo && <button className='button' onClick={generateTEX} {IsSolo &&
<button className='button' onClick={generateTEX}
style={{ style={{
backgroundColor: theme.colors.tertiary, backgroundColor: theme.colors.tertiary,
borderColor: theme.colors.secondary borderColor: theme.colors.secondary

@ -209,7 +209,7 @@ function Lobby() {
</ul> </ul>
<center > <center >
<button className='buttonNabImg' onClick={StartGame}> <button className='buttonNabImg' onClick={StartGame}>
<img src={cible} alt="Button Image" height="50" width="50"/> <img src={cible} alt="Button Image" height="50" width="50" />
<p>{"la chasse !"}</p> <p>{"la chasse !"}</p>
</button> </button>
</center> </center>

@ -8,8 +8,7 @@ import './Play.css';
import { useTheme } from '../Style/ThemeContext'; import { useTheme } from '../Style/ThemeContext';
/* Component */ /* Component */
import ButtonImgNav from "../Components/ButtonImgNav" import ButtonImgNav from "../Components/ButtonImgNav";
import SessionService from "../services/SessionService";
/* Img */ /* Img */
/* Icon */ /* Icon */
@ -23,11 +22,62 @@ import defaultImg from "../res/img/Person.png"
/* Types */ /* Types */
import User from '../model/User'; import User from '../model/User';
import EnigmeDuJourCreator from '../model/EnigmeDuJourCreator';
import Stub from '../model/Stub';
import SessionService from '../services/SessionService';
import { loadImageAsync } from '../ImageHelper'; import { loadImageAsync } from '../ImageHelper';
function Play() { function Play() {
let first = true
const theme=useTheme() const theme=useTheme()
const {isLoggedIn, login, user, setUserData, manager } = useAuth(); 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(); const { setIndicesData, setPersonData, setPersonNetworkData } = useGame();
@ -69,10 +119,24 @@ function Play() {
setPersonNetworkData(networkPerson) setPersonNetworkData(networkPerson)
setIndicesData(choosenIndices) setIndicesData(choosenIndices)
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(() => { useEffect(() => {
const handleLobbyCreated = (newRoom: any) => { const handleLobbyCreated = (newRoom: any) => {
@ -118,6 +182,7 @@ function Play() {
</div> </div>
<div className='buttonGroupVertical'> <div className='buttonGroupVertical'>
<button onClick={launchMastermind} className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Jouer seul </button> <button onClick={launchMastermind} className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Jouer seul </button>
<button onClick={launchEngimeJour} className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Résoudre une énigme</button>
<button onClick={createLobby} className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Créer une partie </button> <button onClick={createLobby} className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Créer une partie </button>
<button className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Rejoindre </button> <button className="ButtonNav" style={{backgroundColor: theme.colors.primary, borderColor: theme.colors.secondary}}> Rejoindre </button>

@ -1,6 +1,5 @@
import { io } from "socket.io-client"; import { io } from "socket.io-client";
import {ADRESSE_WEBSERVER} from "./AdressConfig" import { ADRESSE_WEBSERVER } from "./AdressConfig";
const socket = io(ADRESSE_WEBSERVER); const socket = io(ADRESSE_WEBSERVER);

@ -55,7 +55,7 @@
"color_start": "Le suspect a les cheveux", "color_start": "Le suspect a les cheveux",
"color_end": "", "color_end": "",
"nb_friends_indice_start": "Le suspect", "nb_friends_indice_start": "Le suspect a",
"nb_friends_indice_end": "amis", "nb_friends_indice_end": "amis",
"nb_sports_indice_start": "Le suspect pratique", "nb_sports_indice_start": "Le suspect pratique",

@ -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}

@ -44,6 +44,31 @@ class DbUserService implements IUserService{
} }
} }
async updateSoloStats(pseudo: string, nbGames: number, bestScore: number, avgNbTry: number): Promise<void> {
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<void> {
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 export default DbUserService

@ -1,8 +1,9 @@
import User from "../User"; import User from "../User";
interface IUserService{ interface IUserService{
fetchUserInformation(): Promise<[User | null, boolean]> fetchUserInformation(): Promise<[User | null, boolean]>
updateSoloStats(pseudo: string, nbGames: number, bestScore: number, avgNbTry: number): Promise<void>
updateOnlineStats(pseudo: string, nbGames: number, bestScore: number, ratio: number): Promise<void>
} }

@ -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<number, Pair<Indice, boolean>[]>{
const map = new Map<number, Pair<Indice, boolean>[]>()
personNetwork.getPersons().forEach((p) =>{
map.set(p.getId(), [])
})
console.log("START ENIGME")
choosenIndices.forEach((choosenIndice) => {
const choosenIndiceTester = IndiceTesterFactory.Create(choosenIndice)
const modifiedPersons: Pair<Person, boolean>[] = []
let possibleIndices: Indice[] = [...allIndices]
let i = 0
while (possibleIndices.length != 1){
let tmpPossibleIndices: Indice[] = [...possibleIndices]
let choosenPair : Pair<Person, boolean> = 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<tmpPossibleIndices.length){
tmpPossibleIndices = veryTmpIndice
choosenPair = new Pair(person, false)
}
}
else{
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<tmpPossibleIndices.length){
tmpPossibleIndices = veryTmpIndice
choosenPair = new Pair(person, true)
}
}
}
possibleIndices = [...tmpPossibleIndices]
modifiedPersons.push(choosenPair)
console.log(possibleIndices)
}
console.log("choosenIndice => " + 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

@ -16,7 +16,7 @@ class NbSportIndice extends Indice {
// Implémentation de la méthode abstraite // Implémentation de la méthode abstraite
ToString(lang: string): string { ToString(lang: string): string {
let json = GetJsonFile(lang) let json = GetJsonFile(lang)
let string = `${json.nb_sports_indice_start}`; let string = `${json.nb_sports_indice_start} `;
this.nbSport.forEach((i, index) =>{ this.nbSport.forEach((i, index) =>{
if (index == this.nbSport.length - 1){ if (index == this.nbSport.length - 1){
string += i string += i

@ -16,10 +16,10 @@ class SportIndice extends Indice {
let string = json.sport_start; let string = json.sport_start;
for (let i = 0; i<this.sports.length; i++){ for (let i = 0; i<this.sports.length; i++){
if (i==this.sports.length - 1 || this.sports.length == 1){ if (i==this.sports.length - 1 || this.sports.length == 1){
string = `${string} ${SportToString(this.sports[i], lang)}` string = `${string} ${SportToString(this.sports[i], lang)} `
} }
else{ else{
string = `${string} ${SportToString(this.sports[i], lang)} ${json.or_sport}` string = `${string} ${SportToString(this.sports[i], lang)} ${json.or_sport} `
} }
} }
return `${string} ${json.sport_end}` return `${string} ${json.sport_end}`

@ -22,20 +22,14 @@ class Stub{
let test = 7 let test = 7
for (let i: Color=0; i<5; i++){ for (let i: Color=0; i<5; i++){
for (let j: Color=0; j<5; j++){ for (let j: Color=i + 1; j<5; j++){
if (j==i){
continue
}
indices.push(new ColorIndice(test, [i, j])) indices.push(new ColorIndice(test, [i, j]))
test++ test++
} }
} }
for (let i: Sport=0; i<5; i++){ for (let i: Sport=0; i<5; i++){
for (let j: Sport=0; j<5; j++){ for (let j: Sport=i + 1; j<5; j++){
if (j==i){
continue
}
indices.push(new SportIndice(test, [i, j])) indices.push(new SportIndice(test, [i, j]))
test++ test++
} }

@ -22,7 +22,6 @@
"Riley", "Riley",
"Layla", "Layla",
"Stella", "Stella",
"Aurora",
"Natalie", "Natalie",
"Zoe", "Zoe",
"Lucy", "Lucy",
@ -48,7 +47,6 @@
"Bella", "Bella",
"Sadie", "Sadie",
"Hailey", "Hailey",
"Aurora",
"Liam", "Liam",
"Noah", "Noah",
"Oliver", "Oliver",
@ -69,7 +67,6 @@
"Jack", "Jack",
"Jayden", "Jayden",
"Owen", "Owen",
"Noah",
"Ethan", "Ethan",
"Mason", "Mason",
"Logan", "Logan",
@ -93,4 +90,3 @@
"Julian" "Julian"
] ]
} }

@ -8,6 +8,10 @@ class AuthController {
static async signUp(req, res) { static async signUp(req, res) {
const databaseService = new DatabaseService(); const databaseService = new DatabaseService();
const pseudo = req.body.pseudo; const pseudo = req.body.pseudo;
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
try { try {
await databaseService.connect(); await databaseService.connect();
@ -31,11 +35,9 @@ class AuthController {
const soloStats = await databaseService.getSoloStatsByUserId(user.idUser); const soloStats = await databaseService.getSoloStatsByUserId(user.idUser);
const onlineStats = await databaseService.getOnlineStatsByUserId(user.idUser); const onlineStats = await databaseService.getOnlineStatsByUserId(user.idUser);
console.log(soloStats);
console.log(onlineStats);
await databaseService.updateUserIDStats(user.idUser, soloStats.idSoloStats, onlineStats.idOnlineStats); await databaseService.updateUserIDStats(user.idUser, soloStats.idSoloStats, onlineStats.idOnlineStats);
// Envoyer une réponse réussie
console.log("[" + hour + ":" + minutes + "] " + user.pseudo + " have been registered.");
res.status(201).json({ message: 'Inscription réussie', user: insertedUser}); res.status(201).json({ message: 'Inscription réussie', user: insertedUser});
} }
catch (error) { catch (error) {
@ -50,6 +52,9 @@ class AuthController {
static async signIn(req, res) { static async signIn(req, res) {
const databaseService = new DatabaseService(); const databaseService = new DatabaseService();
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
try{ try{
await databaseService.connect(); await databaseService.connect();
@ -70,12 +75,11 @@ class AuthController {
return; return;
} }
// Stocker l'utilisateur dans la session){ // Stocker l'utilisateur dans la session)
console.log("SESSION")
console.log(req.session);
req.session.user = user; req.session.user = user;
// Envoyer une réponse réussie // Envoyer une réponse réussie
console.log("[" + hour + ":" + minutes + "] " + user.pseudo + " have been connected.");
res.status(200).json({ message: 'Connexion réussie', user: user }); res.status(200).json({ message: 'Connexion réussie', user: user });
} }
catch(error){ catch(error){
@ -89,12 +93,17 @@ class AuthController {
} }
static async logout(req, res) { static async logout(req, res) {
const pseudo = req.session.user.pseudo;
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
// Détruire la session pour déconnecter l'utilisateur // Détruire la session pour déconnecter l'utilisateur
req.session.destroy((err) => { req.session.destroy((err) => {
if (err) { if (err) {
console.error(err); console.error(err);
res.status(500).json({ error: 'Erreur lors de la déconnexion.' }); res.status(500).json({ error: 'Erreur lors de la déconnexion.' });
} else { } else {
console.log("[" + hour + ":" + minutes + "] " + pseudo + " have been disconnected.");
res.status(200).json({ message: 'Déconnexion réussie' }); res.status(200).json({ message: 'Déconnexion réussie' });
} }
}); });

@ -3,6 +3,9 @@ const DatabaseService = require('../services/DatabaseService');
class SessionController { class SessionController {
static async getUserInformation(req, res) { static async getUserInformation(req, res) {
const db = new DatabaseService(); const db = new DatabaseService();
const date = new Date();
const hour = date.getHours();
const minutes = date.getMinutes();
try{ try{
await db.connect(); await db.connect();
@ -15,8 +18,7 @@ class SessionController {
req.session.user.soloStats = await db.getSoloStatsByUserId(req.session.user.idUser); req.session.user.soloStats = await db.getSoloStatsByUserId(req.session.user.idUser);
req.session.user.onlineStats = await db.getOnlineStatsByUserId(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 }); res.status(200).json({ user: req.session.user });
} }
catch(error){ 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){ static async UpdatePseudo(req, res){
const db = new DatabaseService(); const db = new DatabaseService();

@ -12,5 +12,7 @@ router.delete('/auth/delAccount', AuthController.delAccount)
// Routes pour les sessions // Routes pour les sessions
router.get('/session', SessionController.getUserInformation); router.get('/session', SessionController.getUserInformation);
router.put('/session/updatePseudo', SessionController.UpdatePseudo); router.put('/session/updatePseudo', SessionController.UpdatePseudo);
router.put('/session/updateSoloStats', SessionController.updateSoloStats);
router.put('/session/updateOnlineStats', SessionController.updateOnlineStats);
module.exports = router; module.exports = router;

@ -6,13 +6,14 @@ const crypto = require('crypto');
const authRoutes = require('./routes/authRoutes'); const authRoutes = require('./routes/authRoutes');
const DatabaseService = require('./services/DatabaseService'); const DatabaseService = require('./services/DatabaseService');
const app = express(); const app = express();
const port = 3003; const port = 3003;
// Middleware // Middleware
app.use(cors( 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 credentials: true
} }
)); // Autoriser les requêtes cross-origin )); // Autoriser les requêtes cross-origin

@ -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 // Récupère stats solo de l'utilisateur
async getSoloStatsByUserId(userId){ async getSoloStatsByUserId(userId){
return new Promise((resolve, reject) => { 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) { async initSoloStats(userId) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {

@ -1,3 +1,4 @@
import { ADRESSE_DBSERVER } from '../adressConfig';
import VerificationService from './VerificationService'; import VerificationService from './VerificationService';
import {ADRESSE_DBSERVER} from "../AdressConfig" import {ADRESSE_DBSERVER} from "../AdressConfig"
import User from '../model/User'; import User from '../model/User';

@ -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) { static async UpdatePseudo(pseudo : string, newPseudo : string) {
console.log("pseudo : " + pseudo + " newpseudo : " + newPseudo) console.log("pseudo : " + pseudo + " newpseudo : " + newPseudo)
try { try {

Loading…
Cancel
Save