Baptiste MARCEL 1 year ago
commit f55db09007

7
.gitignore vendored

@ -41,4 +41,9 @@ bower_components
psd
thumb
sketch
sketch
# db
socialgraph.db

@ -15,7 +15,6 @@ const io = socketIO(server, {
const map = new Map()
// ... le reste de votre configuration du serveur
server.listen(3002, () => {
console.log('Serveur Socket.IO écoutant sur le port 3002');
@ -29,25 +28,26 @@ io.on('connection', (socket) => {
});
socket.on("lobby joined", (room, player) =>{
if (player.type=="Human"){
console.log(player)
if (player.type=="User"){
socket.join(room)
}
if (map.get(room) == undefined){
map.set(room, [{type: player.type, id: socket.id, name: player.name}])
map.set(room, [{type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture}])
}
else{
const tab = map.get(room)
for(let i = 0; i<tab.length; i++){
if (tab[i].id === socket.id && player.type==="Human"){
if (tab[i].id === socket.id && player.type==="User"){
tab.splice(i, 1)
}
}
if (player.type!=="Human"){
map.get(room).push({type: player.type, id: player.id, name: player.name})
if (player.type!=="User"){
map.get(room).push({type: player.type, id: player.id, pseudo: player.pseudo, profilePicture: player.profilePicture})
}
else{
map.get(room).push({type: player.type, id: socket.id, name: player.name})
map.get(room).push({type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture})
}
}
@ -56,7 +56,6 @@ io.on('connection', (socket) => {
socket.on("bot deleted", (bot, room) =>{
// map.set(room, map.get(room).filter(player => player.id !== bot.id));
const tab = map.get(room)
for(let i = 0; i<tab.length; i++){
if (tab[i].id === bot.id){

@ -61,7 +61,7 @@ const ChoiceBar = () => {
{players.map((player, index) => (
player.id !== socket.id &&
<button key={index} className="choice-bar-button" onClick={() => askPlayer(player.id)} style={{ backgroundColor: theme.colors.primary }}>
{player.name}
{player.pseudo}
</button>
))}
</div>

@ -11,6 +11,7 @@ import { colorToEmoji, positionToColor, positionToEmoji } from "../ColorHelper";
import { ColorToHexa } from "../model/EnumExtender";
import Bot from "../model/Bot";
import NodePerson from "../model/Graph/NodePerson";
import { useAuth } from "../Contexts/AuthContext";
interface MyGraphComponentProps {
@ -22,6 +23,7 @@ interface MyGraphComponentProps {
changecptTour: (newcptTour : number) => void
addToHistory: (message : string) => void
solo : boolean
isDaily : boolean
setNetwork: (network: Network) => void
showLast: boolean
}
@ -38,12 +40,17 @@ let lastSocketId= ""
let firstLap = true
let cptHistory = 0
let lastNodes: NodePerson[] = []
let firstEnigme = true
const MyGraphComponent: React.FC<MyGraphComponentProps> = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, addToHistory, showLast, setNetwork}) => {
let cptTour: number = 0
const MyGraphComponent: React.FC<MyGraphComponentProps> = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, isDaily, addToHistory, showLast, setNetwork}) => {
let cptTour: number = 0
const { indices, indice, person, personNetwork, setNodeIdData, players, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData } = useGame();
//* Gestion du temps :
const initMtn = new Date().getSeconds()
const {user} = 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();
@ -256,6 +263,28 @@ let cptTour: number = 0
setNetwork(network)
if (isDaily){
dailyEnigme.forEach((pairs, index) => {
pairs.forEach((pair) => {
const i = indices.findIndex((indice) => pair.first.getId() === indice.getId())
console.log(index)
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)
if (test!=undefined){
console.log(test.label)
}
}
})
});
}
indices.forEach((i, index) => {
console.log(i.ToString("fr") + " => " + positionToEmoji(index, true))
})
if (!solo){
socket.on("asked all", (id) =>{
const pers = personNetwork.getPersons().find((p) => p.getId() == id)
@ -309,7 +338,7 @@ let cptTour: number = 0
cptHistory++
if (cptHistory % 2 == 0){
lastNodes.push(node)
addToHistory(players[askedIndex].name + " à mis un " + positionToEmoji(askedIndex, works) + " à " + personNetwork.getPersons()[id].getName())
addToHistory(players[askedIndex].pseudo + " à mis un " + positionToEmoji(askedIndex, works) + " à " + personNetwork.getPersons()[id].getName())
}
}
@ -622,7 +651,13 @@ let cptTour: number = 0
works = false
}
if (index == indices.length - 1 && works){
navigate("/endgame")
const Mtn = new Date().getSeconds()
settempsData(Mtn - initMtn)
cptTour ++;
setNbCoupData(cptTour)
navigate("/endgame?solo=true&daily=" + isDaily)
}
}
@ -631,7 +666,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 + "] ----->");

@ -47,7 +47,7 @@ const PlayerItemList:React.FC<MyPlayerItemListProps> =({ player, room }) => {
<div className='item-horizontal-div'>
<div>
<img src={pdp} alt='player-image' height='100' width='100' />
<h4>{player.name}</h4>
<h4>{player.pseudo}</h4>
</div>
{isBot && (
<Button className='suprButton' onClick={delBot} variant="danger">

@ -25,7 +25,7 @@ const PlayerList: React.FC<PlayerListProps> = ({ players, playerTouched, setPlay
{
//@ts-ignore
players.map((player, index) => (
player.id!=socket.id && <PersonStatus img={Person} state={Person} key={index} name={player.name + " " + colorToEmoji(positionToColor(index), true)} playerTouched={playerTouched} setPlayerTouched={setPlayerTouched} index={index} showCircle={true}/>
player.id!=socket.id && <PersonStatus img={Person} state={Person} key={index} name={player.pseudo + " " + colorToEmoji(positionToColor(index), true)} playerTouched={playerTouched} setPlayerTouched={setPlayerTouched} index={index} showCircle={true}/>
))
}
</div>

@ -20,12 +20,12 @@ import Col from 'react-bootstrap/Col';
/* Component */
import ButtonImgNav from './ButtonImgNav';
import User from '../model/User';
/* Types */
import { PlayerProps } from '../types/Player';
//@ts-ignore
const ScoreBoard: React.FC<{ Player: PlayerProps }> = ({ Player }) => {
const ScoreBoard: React.FC<{ Player: User }> = ({ Player }) => {
const theme=useTheme();
return (

@ -1,22 +1,31 @@
// AuthContext.js
import React, { createContext, useContext, useState, ReactNode } from 'react';
import Player from '../model/Player';
import User from '../model/User';
import AuthService from '../services/AuthService';
interface AuthContextProps {
isLoggedIn: boolean;
login: () => void;
logout: () => void;
user: User | null
setUserData: (newPlayer: User) => void
}
const AuthContext = createContext<AuthContextProps | undefined>(undefined);
const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
const [user, setUser] = useState<User| null>(null)
const login = () => {
setIsLoggedIn(true);
};
const setUserData = (player: User | null) => {
setUser(player)
}
const logout = async() => {
try {
await AuthService.logout();
@ -28,7 +37,7 @@ const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
};
return (
<AuthContext.Provider value={{ isLoggedIn, login, logout }}>
<AuthContext.Provider value={{ isLoggedIn, login, logout, user, setUserData }}>
{children}
</AuthContext.Provider>
);

@ -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<number, Pair<Indice, boolean>[]>
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<number, Pair<Indice, boolean>[]>) => void
setNbCoupData: (newNbCoup : number) => void
settempsData: (newtemps : number) => void
}
const GameContext = createContext<GameContextProps | undefined>(undefined);
@ -51,6 +58,9 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
const [room, setRoom] = useState<string>("")
const [onlyFalse, setOnlyFalse] = useState<boolean>(false)
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[]) => {
@ -102,6 +112,19 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
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 = () => {
setIndices([])
setActualPlayerIndex(-1)
@ -114,10 +137,12 @@ export const GameProvider: React.FC<GameProviderProps> = ({ children }) => {
setTurnPlayerIndex(-1)
setNodeId(-1)
setIndice(null)
setNbCoup(0)
settemps(0)
}
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}
</GameContext.Provider>
);

@ -1,5 +1,5 @@
import EasyBot from "./model/EasyBot";
import Human from "./model/Human";
import Human from "./model/User";
import AgeIndice from "./model/Indices/AgeIndice";
import ColorEdgesIndice from "./model/Indices/ColorEdgesIndice";
import ColorIndice from "./model/Indices/ColorIndice";
@ -10,6 +10,7 @@ import SportIndice from "./model/Indices/SportIndice";
import Person from "./model/Person";
import PersonNetwork from "./model/PersonsNetwork";
import Player from "./model/Player";
import User from "./model/User";
class JSONParser{
@ -84,10 +85,10 @@ class JSONParser{
static JSONToPlayer(json: any): Player{
switch (json.type){
case "Human":
return new Human(json.id, json.name)
case "User":
return new User(json.id, json.pseudo, json.profilePicture, json.soloStats, json.onlineStats)
case "EasyBot":
return new EasyBot(json.id, json.name)
return new EasyBot(json.id, json.pseudo, json.profilePicture)
default:
throw new Error("PARSER unable to parse player: " + json.type);
}

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

@ -22,62 +22,126 @@ 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()
const {winner, person, players, indices, nbCoup, temps} =useGame()
console.log(winner)
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 (
<div>
{!IsSolo &&
<div>
<div className="head">
<header className='leaderboard-header' style={{ borderColor: theme.colors.primary }}>
<h1>{winner?.pseudo} a gagné !</h1>
<h3>Le tueur était <u>{person?.getName()}</u></h3>
</header>
</div>
<div className='winner'>
<img src={Person} width='250' height='250'/>
<h3 className='indiceDisplay'>{indices[players.findIndex((p) => p.id == winner?.id)].ToString("fr")}</h3>
</div>
<div className='bottom'>
<div className='centerDivH' onClick={resetAll}>
<BigButtonNav dest="/play" img={Leave}/>
</div>
<div className="losingPlayersContainer">
{losingPlayers.map((player, index) => (
<div className="playerContainer" key={index}>
{player.id !== winner?.id && (
<div>
<PersonStatus img={Person} state={Person} key={index} name={player.pseudo} playerTouched={1} setPlayerTouched={() => {}} index={index} showCircle={false}/>
<h6 className='indiceDisplay'>{indices[players.findIndex((p) => p.id == player?.id)].ToString("fr")}</h6>
</div>
)}
</div>
))}
</div>
<div className='centerDivH'>
<BigButtonNav dest="/lobby" img={Replay}/>
</div>
</div>
</div>
}
<div className="head">
<header className='leaderboard-header' style={{ borderColor: theme.colors.primary }}>
<h1>{winner?.name} a gagné !</h1>
<h3>Le tueur était <u>{person?.getName()}</u></h3>
</header>
<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'/>
<h3 className='indiceDisplay'>{indices[players.findIndex((p) => p.id == winner?.id)].ToString("fr")}</h3>
<h1>[ {winner?.pseudo} ]</h1>
</div>
<div className='bottom'>
<div className='centerDivH' onClick={resetAll}>
<BigButtonNav dest="/play" img={Leave}/>
</div>
<div className="losingPlayersContainer">
{losingPlayers.map((player, index) => (
<div className="playerContainer" key={index}>
{player.id !== winner?.id && (
<div>
<PersonStatus img={Person} state={Person} key={index} name={player.name} playerTouched={1} setPlayerTouched={() => {}} index={index} showCircle={false}/>
<h6 className='indiceDisplay'>{indices[players.findIndex((p) => p.id == player?.id)].ToString("fr")}</h6>
</div>
)}
</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}/>

@ -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<string[]>([]);
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}) => {
</div>
{IsSolo &&
{IsSolo && !isDaily &&
<div className='nbLaps' style={{
backgroundColor: theme.colors.primary,
borderColor: theme.colors.secondary
@ -228,12 +236,13 @@ const InGame = ({locale, changeLocale}) => {
</div>
}
<div className='historique' id="history-container">
{history.map((item, index) => (
<div key={index}>{item}</div>
))}
</div>
{!isDaily &&
<div className='historique' id="history-container">
{history.map((item, index) => (
<div key={index}>{item}</div>
))}
</div>
}
<div className='paramDiv'>
<button className='button'
@ -289,7 +298,8 @@ const InGame = ({locale, changeLocale}) => {
<img src={Check} alt="check" height="40"/>
</button> */}
{!IsSolo && <Link to='/info' target='_blank'>
{!IsSolo &&
<Link to='/info' target='_blank'>
<button className='button'
style={{
backgroundColor: theme.colors.tertiary,
@ -315,13 +325,15 @@ const InGame = ({locale, changeLocale}) => {
<img src={ eye } alt="indice" height="40"/>
</button>}
{IsSolo && <button className='button' onClick={generateTEX}
style={{
backgroundColor: theme.colors.tertiary,
borderColor: theme.colors.secondary
}}>
<img src={Download} alt="indice" height="40"/>
</button>
{IsSolo &&
<button className='button' onClick={generateTEX}
style={{
backgroundColor: theme.colors.tertiary,
borderColor: theme.colors.secondary
}}>
<img src={Download} alt="indice" height="40"/>
</button>
}
</div>
@ -390,9 +402,6 @@ const InGame = ({locale, changeLocale}) => {
</Offcanvas.Body>
</Offcanvas>
<div id="bottom-container">
{showChoiceBar && <ChoiceBar />}
</div>
{/*
<div id="endgamebutton" > {/* tmp
<ButtonImgNav dest="/endgame" img={Leave} text='endgame'/>

@ -22,9 +22,11 @@ import { useNavigate } from 'react-router-dom';
import { socket } from "../SocketConfig";
import { random } from 'lodash';
import Player from '../model/Player';
import Human from '../model/Human';
import EasyBot from '../model/EasyBot';
import Bot from '../model/Bot';
import User from '../model/User';
import { useAuth } from '../Contexts/AuthContext';
import SessionService from '../services/SessionService';
let gameStarted = false
@ -36,23 +38,64 @@ function Lobby() {
const { indices, setIndicesData, indice, setIndiceData, person, setPersonData, personNetwork, setPersonNetworkData, players, setPlayersData, setActualPlayerIndexData, setTurnPlayerIndexData, setRoomData } = useGame();
const {user, setUserData} = useAuth()
let first = true
const params = new URLSearchParams(window.location.search);
const room = params.get('room');
function addBot(){
socket.emit("lobby joined", room, new EasyBot("botId" + Math.floor(Math.random() * 1000), "Bot" + Math.floor(Math.random() * 100)).toJson())
socket.emit("lobby joined", room, new EasyBot("botId" + Math.floor(Math.random() * 1000), "Bot" + Math.floor(Math.random() * 100), "").toJson())
}
// function delBot(selectedBot: Bot){
// }
useEffect(() => {
if (first){
first=false
socket.emit("lobby joined", room, new Human("test", "Test" + Math.floor(Math.random() * 100)).toJson())
if (user == null){
try {
const sessionData = SessionService.getSession();
sessionData.then((s) => {
if (s.user) {
// Il y a une session on récupère les infos du joueur
const updatedPlayer: User = new User(socket.id, s.user.pseudo, s.user.profilePicture, {
nbGames: s.user.soloStats.nbGames,
bestScore: s.user.soloStats.bestScore,
avgNbTry: s.user.soloStats.avgNbTry,
},
{
nbGames: s.user.onlineStats.nbGames,
nbWins: s.user.onlineStats.nbWins,
ratio: s.user.onlineStats.ratio,
})
setUserData(updatedPlayer);
socket.emit("lobby joined", room, updatedPlayer.toJson())
} 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);
socket.emit("lobby joined", room, guestPlayer.toJson())
}
})
}
catch (error) {
console.error(error);
}
}
else{
socket.emit("lobby joined", room, user.toJson())
}
return () => {
socket.off('game created');
@ -114,7 +157,12 @@ function Lobby() {
setPersonData(choosenPerson)
setPersonNetworkData(networkPerson)
setIndicesData(choosenIndices)
let start = 0
let users = players.filter((p) => p instanceof User)
let u = users[Math.floor(Math.random() * users.length)]
let start = players.findIndex((p) => p.id == u.id)
if (start == -1){
start = 0
}
socket.emit('network created', JSON.stringify(networkPerson, null, 2), JSON.stringify(choosenPerson), JSON.stringify(choosenIndices), room, start);
}

@ -23,12 +23,18 @@ import ScoreBoard from '../Components/ScoreBoard';
/* Types */
import { PlayerProps } from '../types/Player';
import Player from '../model/Player';
import Human from '../model/User';
import User from '../model/User';
import EnigmeDuJourCreator from '../model/EnigmeDuJourCreator';
import Stub from '../model/Stub';
let first = true
function Play() {
const theme=useTheme()
const {isLoggedIn, login} = useAuth();
const [player, setPlayer] = useState<PlayerProps | null>(null);
const {isLoggedIn, login, user, setUserData } = useAuth();
const {setDailyEnigmeData} = useGame()
useEffect(() => {
const fetchUserInformation = async () => {
@ -38,48 +44,41 @@ function Play() {
// 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: PlayerProps = {
pseudo: sessionData.user.pseudo,
profilePicture: sessionData.user.profilePicture,
soloStats: {
nbGames: sessionData.user.soloStats.nbGames,
bestScore: sessionData.user.soloStats.bestScore,
avgNbTry: sessionData.user.soloStats.avgNbTry,
},
onlineStats: {
nbGames: sessionData.user.onlineStats.nbGames,
nbWins: sessionData.user.onlineStats.nbWins,
ratio: sessionData.user.onlineStats.ratio,
},
};
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();
setPlayer(updatedPlayer);
setUserData(updatedPlayer);
} else {
// Pas de session on génère un guest random
const guestPlayer: PlayerProps = {
pseudo: 'Guest_' + Math.floor(Math.random() * 1000000),
profilePicture: '',
soloStats: {
nbGames: 0,
bestScore: 0,
avgNbTry: 0,
},
onlineStats: {
nbGames: 0,
nbWins: 0,
ratio: 0,
},
};
setPlayer(guestPlayer);
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();
@ -97,10 +96,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) => {
@ -136,7 +149,7 @@ function Play() {
<div className="MidContainer">
<div>
<h2>
{player && player.pseudo}
{user && user.pseudo}
</h2>
<img src={Person}
height='300'
@ -146,13 +159,14 @@ function Play() {
</div>
<div className='buttonGroupVertical'>
<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}}> Jouer seul mais aujourd'hui</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>
</div>
</div>
<div className='rightContainer'>
{player && (<ScoreBoard Player={player}/>)}
{user && (<ScoreBoard Player={user}/>)}
</div>
</div>
);

@ -1,6 +1,6 @@
import { io } from "socket.io-client";
const socket = io("http://localhost:3002");
const socket = io("http://172.20.10.4:3002");
export {socket}

@ -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",

@ -13,8 +13,8 @@ abstract class Bot extends Player{
public actualNetwork: Map<Person, Pair<number, boolean>[]>
constructor( id: string, name: string){
super(id, name);
constructor( id: string, name: string, profilePicture: string){
super(id, name, profilePicture);
this.actualNetwork = new Map<Person, Pair<number, boolean>[]>()
this.index = -1

@ -11,15 +11,16 @@ import Player from "./Player";
class EasyBot extends Bot{
constructor(id: string, name: string){
super(id, name)
constructor(id: string, name: string, profilePicture: string){
super(id, name, profilePicture)
}
toJson() {
return {
type: "EasyBot",
id: this.id,
name: this.name,
pseudo: this.pseudo,
profilePicture: this.profilePicture
};
}

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

@ -1,18 +0,0 @@
import Player from "./Player";
class Human extends Player{
constructor(id: string, name: string){
super(id, name)
}
toJson() {
return {
type: "Human",
id: this.id,
name: this.name,
};
}
}
export default Human

@ -1,10 +1,13 @@
abstract class Player{
public id: string
public name: string;
public pseudo: string;
public profilePicture: string
constructor(id: string, name: string){
constructor(id: string, pseudo: string, profilePicture: string){
this.id=id
this.name=name
this.pseudo=pseudo
this.profilePicture=profilePicture
}
abstract toJson(): any

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

@ -0,0 +1,25 @@
import Player from "./Player";
class User extends Player{
public soloStats: any
public onlineStats: any
constructor(id: string, name: string, profilePicture: string, soloStats: any, onlineStats: any){
super(id, name, profilePicture)
this.soloStats=soloStats
this.onlineStats=onlineStats
}
toJson() {
return {
type: "User",
id: this.id,
pseudo: this.pseudo,
soloStats: this.soloStats,
onlineStats: this.onlineStats
};
}
}
export default User

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

@ -71,6 +71,7 @@ class AuthController {
}
// Stocker l'utilisateur dans la session){
console.log("SESSION")
console.log(req.session);
req.session.user = user;

@ -12,7 +12,7 @@ const port = 3003;
// Middleware
app.use(cors(
{
origin: 'http://localhost:3000',
origin: ['http://localhost:3000', "http://172.20.10.4:3000"],
credentials: true
}
)); // Autoriser les requêtes cross-origin

@ -12,7 +12,7 @@ class AuthService{
static async signUp(data: any) {
try {
const response = await fetch('http://localhost:3003/auth/signup', {
const response = await fetch('http://172.20.10.4:3003/auth/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -36,7 +36,7 @@ class AuthService{
static async signIn(data: any) {
try {
const response = await fetch('http://localhost:3003/auth/signin', {
const response = await fetch('http://172.20.10.4:3003/auth/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -61,7 +61,7 @@ class AuthService{
static async logout() {
try {
const response = await fetch('http://localhost:3003/auth/logout', {
const response = await fetch('http://172.20.10.4:3003/auth/logout', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',

@ -1,7 +1,7 @@
class SessionService {
static async getSession() {
try {
const response = await fetch('http://localhost:3003/session', {
const response = await fetch('http://172.20.10.4:3003/session', {
method: 'GET',
headers: {
'Content-Type': 'application/json',

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save