diff --git a/cryptide_project/server/server.js b/cryptide_project/server/server.js index 725ea1a..6d3511d 100644 --- a/cryptide_project/server/server.js +++ b/cryptide_project/server/server.js @@ -14,6 +14,7 @@ const io = socketIO(server, { }); +let lastSocketJoined = "" const map = new Map() server.listen(3002, () => { @@ -25,18 +26,61 @@ io.on('connection', (socket) => { socket.on('network created', (network, person, indices, room, start) =>{ io.to(room).emit("game created", network, person, indices, start) + map.get(room).started = true + map.get(room).actualPlayer=start + const playerArray = Array.from(map.entries()).map(([key, value]) => ({ key, value })) + const playerJson = JSON.stringify(playerArray); + io.emit("request lobbies", playerJson) }); + socket.on("give network", (networkPerson, person, indices, start, room, nodes, playerId) => { + io.to(playerId).emit("join during game", networkPerson, person, indices, start, map.get(room).tab, nodes) + }) + + socket.on("join back game", (player) => { + for (const k of map.keys()){ + const tab = map.get(k) + for (let i = 0; i{ - console.log(player) - if (player.type=="User"){ - socket.join(room) + + const game = map.get(room) + if (game !== undefined){ + if (game.tab.length == 6 && !game.started){ + io.to(socket.id).emit("room full") + return + } + if (game.started){ + for(const u of game.tab){ + if(u.type !== "User" && u.pseudo===player.pseudo){ + u.type = "User" + u.id=socket.id + io.to(game.tab[game.actualPlayer].id).emit("give network", socket.id) + io.to(room).emit("player joined ingame", game.tab) + socket.join(room) + return + } + } + io.to(socket.id).emit("game already started") + return + } } - if (map.get(room) == undefined){ - map.set(room, [{type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture}]) + + + if (game == undefined){ + map.set(room, {tab: [{type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture}], started: false, actualPlayer: 0, lastWorks: false}) + socket.join(room) } else{ - const tab = map.get(room) + const tab = game.tab for(let i = 0; i { } if (player.type!=="User"){ - map.get(room).push({type: player.type, id: player.id, pseudo: player.pseudo, profilePicture: player.profilePicture}) + tab.push({type: player.type, id: player.id, pseudo: player.pseudo, profilePicture: player.profilePicture}) } else{ - map.get(room).push({type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture}) + tab.push({type: player.type, id: socket.id, pseudo: player.pseudo, profilePicture: player.profilePicture}) + socket.join(room) } } io.to(room).emit("new player", map.get(room)) const playerArray = Array.from(map.entries()).map(([key, value]) => ({ key, value })) const playerJson = JSON.stringify(playerArray); - io.to(socket.id).emit("request lobbies", playerJson) + io.emit("request lobbies", playerJson) + }) socket.on("request lobbies", () => { @@ -65,7 +111,7 @@ io.on('connection', (socket) => { socket.on("bot deleted", (bot, room) =>{ - const tab = map.get(room) + const tab = map.get(room).tab for(let i = 0; i { io.to(room).emit("new player", map.get(room)) const playerArray = Array.from(map.entries()).map(([key, value]) => ({ key, value })) const playerJson = JSON.stringify(playerArray); - io.to(socket.id).emit("request lobbies", playerJson) + io.emit("request lobbies", playerJson) }) @@ -98,22 +144,80 @@ io.on('connection', (socket) => { io.to(askingPlayer.id).emit("asked wrong") }) + socket.on("who plays", (room) => { + if (map.get(room) !== undefined){ + let player = map.get(room).actualPlayer + if (map.get(room).tab[player].type != "User"){ + player = player + 1 + if (player == map.get(room).tab.length){ + player=0 + } + } + console.log(player) + io.to(room).emit("who plays", player, map.get(room).lastWorks) + } + }) + socket.on("disconnect", () =>{ for (const k of map.keys()){ const tab = map.get(k) - for (let i = 0; i p.type=="User").length == 0){ + for (let i = 0; i p.type=="User").length == 0){ map.delete(k) } } } } + const playerArray = Array.from(map.entries()).map(([key, value]) => ({ key, value })) + const playerJson = JSON.stringify(playerArray); + io.emit("request lobbies", playerJson) + }) + + + socket.on("player quit", () => { + lastSocketJoined="" + for (const k of map.keys()){ + const tab = map.get(k) + for (let i = 0; i p.type=="User").length == 0){ + map.delete(k) + } + } + } + } + const playerArray = Array.from(map.entries()).map(([key, value]) => ({ key, value })) + const playerJson = JSON.stringify(playerArray); + io.emit("request lobbies", playerJson) }) socket.on("node checked", (id, works, color, room, playerIndex) =>{ + map.get(room).actualPlayer=playerIndex + map.get(room).lastWorks=works io.to(room).emit("node checked", id, works, color, playerIndex, socket.id) }) @@ -147,5 +251,17 @@ io.on('connection', (socket) => { socket.on("end game", (winnerIndex, room) =>{ io.to(room).emit("end game", winnerIndex) + map.delete(room) }) }); + + +function comparePlayersByType(a, b) { + if (a.type < b.type) { + return -1; + } else if (a.type > b.type) { + return 1; + } else { + return 0; + } +} diff --git a/cryptide_project/src/Components/GraphContainer.tsx b/cryptide_project/src/Components/GraphContainer.tsx index d6f7755..6e39fbb 100644 --- a/cryptide_project/src/Components/GraphContainer.tsx +++ b/cryptide_project/src/Components/GraphContainer.tsx @@ -14,6 +14,10 @@ import NodePerson from "../model/Graph/NodePerson"; import { useAuth } from "../Contexts/AuthContext"; import Indice from "../model/Indices/Indice"; import Pair from "../model/Pair"; +import Player from "../model/Player"; +import JSONParser from "../JSONParser"; +import User from "../model/User"; +import { json } from "body-parser"; interface MyGraphComponentProps { onNodeClick: (shouldShowChoiceBar: boolean) => void; @@ -53,6 +57,11 @@ let endgame= false let firstHistory = true let cptSquare = 0 let cptOnAskedWrong = 0 +let cptPlayerLeft = 0 +let firstPlayer = 0 +let cptBug = 0 +let cptUseEffect = 0 +let testPlayers: Player[] = [] const MyGraphComponent: React.FC = ({onNodeClick, handleShowTurnBar, handleTurnBarTextChange, playerTouched, setPlayerTouched, changecptTour, solo, isDaily, isEasy, addToHistory, showLast, setNetwork, setNetworkEnigme, setPlayerIndex, askedWrong, setAskedWrong}) => { @@ -62,7 +71,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS let initMtn = 0 const {isLoggedIn, user, manager} = useAuth(); - const { indices, indice, person, personNetwork, setNodeIdData, players, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData, dailyEnigme, setNbCoupData, settempsData, setNetworkDataData, setSeedData} = useGame(); + const { indices, indice, person, personNetwork, setNodeIdData, players, setPlayersData, askedPersons, setActualPlayerIndexData, room, actualPlayerIndex, turnPlayerIndex, setTurnPlayerIndexData, setWinnerData, dailyEnigme, setNbCoupData, settempsData, setNetworkDataData, setSeedData, nodesC} = useGame(); const params = new URLSearchParams(window.location.search); const navigate = useNavigate(); @@ -76,6 +85,13 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS setElapsedTime((prevElapsedTime) => prevElapsedTime + 0.5); settempsData(elapsedTime) + cptBug ++ + if (cptBug > 10){ + cptBug = 0 + socket.emit("who plays", room) + } + + // Vérifiez si la durée est écoulée, puis arrêtez le timer if (endgame) { clearInterval(intervalId); @@ -87,8 +103,14 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS }, [elapsedTime, endgame]); + useEffect(() => { + testPlayers = players + console.log(testPlayers) + }, [players]) + useEffect(() =>{ touchedPlayer=playerTouched + console.log(playerTouched) if (touchedPlayer == -1){ if (!askedWrongLocal){ socket.emit("put correct background", socket.id) @@ -140,8 +162,9 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } useEffect(() =>{ - if (actualPlayerIndex==0){ - const bot = players[lastIndex] + cptBug=0 + if (actualPlayerIndex==firstPlayer){ + const bot = testPlayers[lastIndex] if(bot instanceof Bot && botIndex != lastIndex){ botIndex = lastIndex if (personNetwork!=null){ @@ -165,7 +188,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } const tester = IndiceTesterFactory.Create(indices[playerIndex]) const works = tester.Works(person) - socket.emit("asked all 1by1", person.getId(), players[playerIndex].id) + socket.emit("asked all 1by1", person.getId(), testPlayers[playerIndex].id) if (i==players.length){ socket.emit("node checked", personIndex, works, playerIndex, room, nextPlayerIndex) } @@ -174,9 +197,8 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } if(!works){ socket.emit("node checked", personIndex, works, playerIndex, room, nextPlayerIndex) - const ind = bot.placeSquare(personNetwork, players) + const ind = bot.placeSquare(personNetwork, testPlayers) if (ind == -1 ){ - addToHistory(lastIndex.toString() + "177") socket.emit("can't put square", lastIndex, room) return } @@ -194,7 +216,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } else{ if (person!=undefined){ - if (players[choosedPlayerIndex] instanceof Bot){ + if (testPlayers[choosedPlayerIndex] instanceof Bot){ console.log("BOT") const tester = IndiceTesterFactory.Create(indices[choosedPlayerIndex]) const works = tester.Works(person) @@ -209,9 +231,8 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS else{ console.log(lastIndex + " interroge " + choosedPlayerIndex + " a propos de " + person.getName() + " et dit non") socket.emit("node checked", personIndex, false, choosedPlayerIndex, room, lastIndex) - const ind = bot.placeSquare(personNetwork, players) + const ind = bot.placeSquare(personNetwork, testPlayers) if (ind == -1 ){ - addToHistory(lastIndex.toString() + "212") socket.emit("can't put square", playerIndex, room) return } @@ -225,13 +246,12 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } else{ console.log(choosedPlayerIndex + " => Pas bot" ) - socket.emit("ask player", personIndex, players[choosedPlayerIndex].id, players[lastIndex]) + socket.emit("ask player", personIndex, testPlayers[choosedPlayerIndex].id, testPlayers[lastIndex]) console.log(lastIndex + " interroge " + +choosedPlayerIndex + " sur " + personNetwork.getPersons()[personIndex].getName()) const tester = IndiceTesterFactory.Create(indices[choosedPlayerIndex]) if (!tester.Works(person)){ - const ind = bot.placeSquare(personNetwork, players) + const ind = bot.placeSquare(personNetwork, testPlayers) if (ind == -1 ){ - addToHistory(lastIndex.toString() + "232") socket.emit("can't put square", playerIndex, room) return } @@ -275,19 +295,6 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } } - //* fonction qui reinitialise le graphe - const resGraph = () => { //? comment accéder au nework ?? - const savedGraphStateString = localStorage.getItem('graphState'); - if (savedGraphStateString !== null) { - const savedGraphState = JSON.parse(savedGraphStateString); - //network.setData(savedGraphState); - } else { - // La clé 'graphState' n'existe pas dans le localStorage, prenez une action en conséquence. - console.log("ayoooooo"); - } - - }; - useEffect(() => { if (personNetwork == null){ return @@ -307,7 +314,10 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS return; } // Charger les données dans le graph - const nodes = new DataSet(graph.nodesPerson); + let nodes = new DataSet(graph.nodesPerson); + if (nodesC.length != 0){ + nodes = new DataSet(nodesC) + } // Configuration des options du Graphe const initialOptions = { @@ -319,7 +329,6 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS direction: 'LR', // LR (Left to Right) ou autre selon votre préférence sortMethod: 'hubsize' }, - distanceMin: 500, // Set the minimum distance between nodes //randomSeed: 2 }, physics: { @@ -368,6 +377,83 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } } + socket.on("give network", (playerId) => { + socket.emit("give network", JSON.stringify(personNetwork, null, 2), JSON.stringify(person), JSON.stringify(indices), playerIndex, room, JSON.stringify(nodes.get()), playerId); + }) + + socket.on("player joined ingame", (tab) => { + const tmpTab: Player[] = [] + let ind =0 + for (const p of tab){ + if (p.type === "User"){ + tmpTab.push(JSONParser.JSONToPlayer(p)) + } + else{ + tmpTab.push(testPlayers[ind]) + } + ind ++ + } + setPlayersData(tmpTab) + }) + + socket.on("player left ingame", (tab, i) => { + cptPlayerLeft ++ + if (cptPlayerLeft % 2 == 0){ + const tmpTab: Player[] = [] + let ind =0 + for (const p of tab.tab){ + if (ind === i || p.type === "User"){ + tmpTab.push(JSONParser.JSONToPlayer(p)) + } + else{ + tmpTab.push(testPlayers[ind]) + } + ind ++ + } + if (i==firstPlayer){ + for(let index = 0; index < tmpTab.length; index++){ + const test = tmpTab[index] + if (test instanceof User){ + firstPlayer=index + break + } + } + if (actualPlayerIndex==firstPlayer){ + tmpTab.forEach((p, index) =>{ + if (p instanceof Bot && personNetwork!=null){ + p.indice=indices[index] + p.index=index + p.initiateMap(personNetwork) + console.log(p.indice.ToString("fr")) + } + }) + } + } + else{ + const bot = tmpTab[i] + if (bot instanceof Bot && personNetwork != null){ + bot.indice=indices[i] + bot.index=index + bot.initiateMap(personNetwork) + console.log(bot.indice.ToString("fr")) + } + } + if (i==playerIndex){ + playerIndex = lastIndex + 1 + if(playerIndex == players.length){ + playerIndex = 0 + } + setPlayerIndex(playerIndex) + setLastIndex(playerIndex) + if (playerIndex===actualPlayerIndex){ + handleTurnBarTextChange("À vous de jouer") + handleShowTurnBar(true) + } + } + setPlayersData(tmpTab) + } + }) + socket.on("reset graph", () => { console.log("reset graph") initialOptions.physics.enabled = true @@ -375,6 +461,16 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS }) if (!solo){ + + socket.on("who plays", (index) => { + playerIndex=index + setPlayerIndex(index) + setLastIndex(index) + if (actualPlayerIndex==index){ + handleShowTurnBar(true) + } + }) + socket.on("asked all", (id) =>{ //@ts-ignore const pers = personNetwork.getPersons().find((p) => p.getId() == id) @@ -401,12 +497,15 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS }) socket.on("node checked",(id, works, askedIndex, newPlayerIndex, socketId) => { + cptBug=0 //@ts-ignore const node = nodes.get().find((n) => id == n.id) if (node!=undefined){ onNodeClick(false) playerIndex = newPlayerIndex setPlayerIndex(playerIndex) + setLastIndex(newPlayerIndex) + console.log(newPlayerIndex) //@ts-ignore if (mapIndexPersons.get(askedIndex)?.find((p) => p.getId() == id) == undefined){ //@ts-ignore @@ -415,7 +514,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS if (p!=undefined && tab != undefined){ tab.push(p) if (actualPlayerIndex == 0){ - players.forEach((player) => { + testPlayers.forEach((player) => { if (player instanceof Bot){ player.newInformation(p, askedIndex, works) } @@ -429,7 +528,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS cptHistory++ if (cptHistory % 2 == 0){ lastNodes.push(node) - addToHistory(players[askedIndex].pseudo + " à mis un " + positionToEmoji(askedIndex, works) + " à " + personNetwork.getPersons()[id].getName()) + addToHistory(testPlayers[askedIndex].pseudo + " à mis un " + positionToEmoji(askedIndex, works) + " à " + personNetwork.getPersons()[id].getName()) } } @@ -489,9 +588,10 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS }) socket.on("can't put square", (askingPlayer) => { + cptBug=0 cptOnAskedWrong ++ if (cptOnAskedWrong % 2 == 0){ - addToHistory(players[askingPlayer].pseudo + " ne peut plus poser de carré") + addToHistory(testPlayers[askingPlayer].pseudo + " ne peut plus poser de carré") playerIndex = askingPlayer + 1 if(playerIndex == players.length){ playerIndex = 0 @@ -511,6 +611,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS socket.on("asked", (nodeId, askingPlayer) => { + if (askingPlayer.id !== lastAskingPlayer || nodeId !== lastNodeId ){ lastAskingPlayer = askingPlayer.id lastNodeId = nodeId @@ -535,8 +636,8 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS socket.emit("node checked", nodeId, true, actualPlayerIndex, room, playerIndex) } else{ - let index = players.findIndex((p) => p.id == askingPlayer.id) - if (players[index] instanceof Bot){ + let index = testPlayers.findIndex((p) => p.id == askingPlayer.id) + if (testPlayers[index] instanceof Bot){ index = playerIndex + 1 if(index == players.length){ index = 0 @@ -647,6 +748,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS askedWrongBot=false endgame = true firstHistory=true + cptBug=0 try{ if(isLoggedIn){ if(!solo){ @@ -684,6 +786,7 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS socket.off("put correct background") socket.off("put grey background") socket.off("put imossible grey") + socket.off("who plays") navigate("/endgame") } @@ -721,7 +824,9 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS network.on("click", async (params) => { if(params.nodes.length > 0){ + console.log(touchedPlayer) setNodeIdData(params.nodes[0]) + console.log(players) // addToHistory("Le joueur a cliqué") //! TEST DEBUG if (!solo){ if (askedWrongLocal){ @@ -752,7 +857,9 @@ const MyGraphComponent: React.FC = ({onNodeClick, handleS } else if(touchedPlayer != -1 && playerIndex == actualPlayerIndex && touchedPlayer = ({onNodeClick, handleS } else{ if (touchedPlayer >= 0){ - console.log(touchedPlayer) + console.log("CE N'EST PAS UN BOT") //@ts-ignore socket.emit("ask player", params.nodes[0], players[touchedPlayer].id, players.find((p) => p.id === socket.id, actualPlayerIndex)) socket.emit("put correct background", socket.id) diff --git a/cryptide_project/src/Components/LobbyContainer.tsx b/cryptide_project/src/Components/LobbyContainer.tsx index 8a184f3..4c4fe51 100644 --- a/cryptide_project/src/Components/LobbyContainer.tsx +++ b/cryptide_project/src/Components/LobbyContainer.tsx @@ -13,15 +13,13 @@ interface LobbyContainerProps { roomNum : string HeadPlayer : Player nbPlayer : number + setFirst: (first: boolean) => void //? mettre un "nbplayermax" si le nombre de joueur max peut etre fixé ? } -const LobbyContainer: React.FC = ({roomNum, HeadPlayer, nbPlayer}) => { +const LobbyContainer: React.FC = ({roomNum, HeadPlayer, nbPlayer, setFirst}) => { const theme=useTheme(); - - - const navigate = useNavigate(); const dest = '/lobby?room=' + roomNum; @@ -39,6 +37,7 @@ const LobbyContainer: React.FC = ({roomNum, HeadPlayer, nbP else{ if (nbPlayer < 6) { socket.off("request lobbies") + setFirst(true) navigate(dest); } else { handleShow() diff --git a/cryptide_project/src/Components/PersonStatus.tsx b/cryptide_project/src/Components/PersonStatus.tsx index 7ec2942..4bf7415 100644 --- a/cryptide_project/src/Components/PersonStatus.tsx +++ b/cryptide_project/src/Components/PersonStatus.tsx @@ -51,6 +51,7 @@ const PersonStatus: React.FC = ({img = Person, state= Person, function onTouch(){ if (IsActualPlayer && !askedWrong){ setPlayerTouched(index) + setTouchedPlayer(index) } } diff --git a/cryptide_project/src/Contexts/GameContext.tsx b/cryptide_project/src/Contexts/GameContext.tsx index 3dba918..9910e73 100644 --- a/cryptide_project/src/Contexts/GameContext.tsx +++ b/cryptide_project/src/Contexts/GameContext.tsx @@ -1,4 +1,6 @@ import React, { createContext, useContext, useState, ReactNode } from 'react'; +import { DataSet, Edge } from 'vis-network'; +import NodePerson from '../model/Graph/NodePerson'; import Indice from '../model/Indices/Indice'; import Pair from '../model/Pair'; import Person from '../model/Person'; @@ -23,6 +25,7 @@ interface GameContextProps { temps : number networkData: any seed: number | string; + nodesC: NodePerson[] setIndicesData: (newIndices: Indice[]) => void; setIndiceData: (newIndice: Indice) => void; setPersonData: (newPerson: Person) => void; @@ -41,6 +44,7 @@ interface GameContextProps { settempsData: (newtemps : number) => void setNetworkDataData: (networkData: any) => void setSeedData: (seed: number | string) => void + setNodesData: (nodes: NodePerson[]) => void } const GameContext = createContext(undefined); @@ -67,6 +71,12 @@ export const GameProvider: React.FC = ({ children }) => { const [temps, settemps] = useState(0); const [networkData, setNetworkData] = useState(null); const [seed, setSeed] = useState(0); + const [nodesC, setNodes] = useState([]); + + + const setNodesData = (nodes: NodePerson[]) => { + setNodes(nodes) + } const setNetworkDataData = (networkData: any) => { setNetworkData(networkData); @@ -155,7 +165,7 @@ export const GameProvider: React.FC = ({ children }) => { } return ( - + {children} ); diff --git a/cryptide_project/src/JSONParser.ts b/cryptide_project/src/JSONParser.ts index d07560b..9f9e3f0 100644 --- a/cryptide_project/src/JSONParser.ts +++ b/cryptide_project/src/JSONParser.ts @@ -11,6 +11,8 @@ import Person from "./model/Person"; import PersonNetwork from "./model/PersonsNetwork"; import Player from "./model/Player"; import User from "./model/User"; +import NodePerson from "./model/Graph/NodePerson"; +import Font from "./model/Graph/Font"; class JSONParser{ @@ -93,6 +95,15 @@ class JSONParser{ throw new Error("PARSER unable to parse player: " + json.type); } } + + + static JSONToNodePersons(json: any): NodePerson[]{ + const tmpTab: NodePerson[] = [] + json.forEach((element: any) => { + tmpTab.push(new NodePerson(element.id, element.label, element.color, new Font(element.font.color, element.font.size, element.font.align), element.shape)) + }); + return tmpTab + } } export default JSONParser \ No newline at end of file diff --git a/cryptide_project/src/Pages/InGame.tsx b/cryptide_project/src/Pages/InGame.tsx index 887294c..04d5414 100644 --- a/cryptide_project/src/Pages/InGame.tsx +++ b/cryptide_project/src/Pages/InGame.tsx @@ -28,7 +28,7 @@ import Ceye from "../res/icon/hidden.png"; import JSZip from 'jszip'; /* nav */ -import { Link } from 'react-router-dom'; +import { Link, Navigate, useNavigate, useNavigationType } from 'react-router-dom'; /* Boostrap */ import Button from 'react-bootstrap/Button'; @@ -50,13 +50,25 @@ import {generateLatexCode, generateLatexCodeEnigme} from '../Script/LatexScript' import Pair from '../model/Pair'; import Indice from '../model/Indices/Indice'; +let cptNavigation = 0 + //@ts-ignore const InGame = ({locale, changeLocale}) => { const theme = useTheme(); + const navigate = useNavigate() const params = new URLSearchParams(window.location.search); + + const navigationType = useNavigationType() + cptNavigation++ + if (cptNavigation % 2 == 0){ + if (navigationType.toString() == "POP"){ + socket.emit("player quit") + navigate("/play") + } + } //* Gestion solo let IsSolo: boolean = true diff --git a/cryptide_project/src/Pages/Lobbies.tsx b/cryptide_project/src/Pages/Lobbies.tsx index 0ffd2ad..1635e34 100644 --- a/cryptide_project/src/Pages/Lobbies.tsx +++ b/cryptide_project/src/Pages/Lobbies.tsx @@ -10,25 +10,30 @@ import User from '../model/User'; import { socket } from '../SocketConfig'; import JSONParser from '../JSONParser'; import Person from '../model/Person'; +import { useNavigationType } from 'react-router-dom'; class LobbyDataProps { roomNum : string headPlayer: Player nbPlayer: number + started: boolean - constructor(roomNum: string, player: Player, nbPlayer: number){ + constructor(roomNum: string, player: Player, nbPlayer: number, started: boolean){ this.roomNum = roomNum this.headPlayer = player this.nbPlayer = nbPlayer + this.started=started } } +let cptNavigation = 0 + function Lobbies() { const theme=useTheme(); - + const [first, setFirst] = useState(true) const [lobbyData, setLobbyData] = useState([]) @@ -39,19 +44,37 @@ function Lobbies() { lobby.headPlayer.pseudo.toLowerCase().includes(searchTerm.toLowerCase()) ); - useEffect(() => { - socket.emit("request lobbies") + const setFirstData = (first: boolean) => { + setFirst(first) + } + + const navigationType = useNavigationType() + cptNavigation++ + if (cptNavigation % 2 == 0){ + if (navigationType.toString() == "POP"){ + socket.emit("player quit") + } + } + + if (first){ + setFirst(false) + socket.emit("request lobbies") + } + useEffect(() => { socket.on("request lobbies", (map) => { + console.log("wesh") const jsonMap = JSON.parse(map) const tmpTab: LobbyDataProps[]=[] for(const item of jsonMap){ - tmpTab.push(new LobbyDataProps(item.key, JSONParser.JSONToPlayer(item.value[0]), item.value.length)) + tmpTab.push(new LobbyDataProps(item.key, JSONParser.JSONToPlayer(item.value.tab[0]), item.value.tab.length, item.value.started)) } - setLobbyData(tmpTab ) + setLobbyData(tmpTab) }) - }) + }, []) + + return(
@@ -70,6 +93,7 @@ function Lobbies() { roomNum={lobby.roomNum} HeadPlayer={lobby.headPlayer} nbPlayer={lobby.nbPlayer} + setFirst={setFirstData} /> ))}
diff --git a/cryptide_project/src/Pages/Lobby.tsx b/cryptide_project/src/Pages/Lobby.tsx index adefb48..7083ec5 100644 --- a/cryptide_project/src/Pages/Lobby.tsx +++ b/cryptide_project/src/Pages/Lobby.tsx @@ -45,15 +45,17 @@ import SessionService from '../services/SessionService'; import { useRef } from 'react'; import Button from 'react-bootstrap/Button'; import Overlay from 'react-bootstrap/Overlay'; +import { DataSet } from 'vis-network'; let gameStarted = false +let firstLaunch = true function Lobby() { const theme=useTheme(); const navigate = useNavigate(); - const { indices, setIndicesData, indice, setIndiceData, person, setPersonData, personNetwork, setPersonNetworkData, players, setPlayersData, setActualPlayerIndexData, setTurnPlayerIndexData, setRoomData } = useGame(); + const { indices, setIndicesData, indice, setIndiceData, person, setPersonData, personNetwork, setPersonNetworkData, players, setPlayersData, setActualPlayerIndexData, setTurnPlayerIndexData, setRoomData, setNodesData } = useGame(); const {user, setUserData, manager, login} = useAuth() let first = true @@ -130,25 +132,77 @@ function Lobby() { setIndicesData(choosenIndices) first = true gameStarted = true - socket.off("player left") - socket.off("new player") + //socket.off("player left") + //socket.off("new player") + navigate('/game?solo=false&daily=false'); + }); + + + socket.on("join during game", (jsonNetwork, jsonPersonString, jsonIndicesString, playerIndex, players, nodes)=> { + const jsonPerson = JSON.parse(jsonPersonString) + const networkPerson: PersonNetwork = JSONParser.JSONToNetwork(jsonNetwork) + const choosenOne: Person = networkPerson.getPersons().filter((i) => i.getId() == jsonPerson.id)[0] + const choosenIndices : Indice[] = JSONParser.JSONToIndices(jsonIndicesString) + for (let i=0; i{ const tmpTab: Player[] = [] - for (const p of tab){ + for (const p of tab.tab){ tmpTab.push(JSONParser.JSONToPlayer(p)) } console.log(tmpTab) setPlayersData(tmpTab) }) + socket.on("room full", () => { + //TODO POP UP pour quand la room est pleine + navigate("/play") + }) + + socket.on("game started", () => { + //TODO POP UP pour quand la room est pleine + navigate("/play") + }) + + socket.on("game already started", () => { + //TODO POP UP pour quand la room est pleine + navigate("/play") + }) + socket.on("player left", (tab, i) => { const tmpTab: Player[] = [] - for (const p of tab){ + for (const p of tab.tab){ tmpTab.push(JSONParser.JSONToPlayer(p)) } + console.log(tmpTab) setPlayersData(tmpTab) }) @@ -214,7 +268,7 @@ function Lobby() { // ))} -
+ {(players.length < 6) &&
+ }
diff --git a/cryptide_project/src/Pages/Play.tsx b/cryptide_project/src/Pages/Play.tsx index 5c28831..83106db 100644 --- a/cryptide_project/src/Pages/Play.tsx +++ b/cryptide_project/src/Pages/Play.tsx @@ -2,7 +2,6 @@ import React, { useEffect, useRef, useState } from 'react'; /* Context */ import { useAuth } from '../Contexts/AuthContext'; - /* Style */ import './Play.css'; import { useTheme } from '../Style/ThemeContext'; @@ -13,7 +12,7 @@ import ButtonImgNav from "../Components/ButtonImgNav"; /* Img */ /* Icon */ import { socket } from '../SocketConfig'; -import { useNavigate } from 'react-router-dom'; +import { NavigationType, useNavigate, useNavigationType } from 'react-router-dom'; import GameCreator from '../model/GameCreator'; import { useGame } from '../Contexts/GameContext'; import ScoreBoard from '../Components/ScoreBoard'; @@ -32,6 +31,9 @@ import Button from 'react-bootstrap/Button'; import ButtonGroup from 'react-bootstrap/ButtonGroup'; +let cptNavigation = 0 + + function Play() { let first = true @@ -41,6 +43,16 @@ function Play() { const target = useRef(null); + const navigationType = useNavigationType() + cptNavigation++ + if (cptNavigation % 2 == 0){ + if (navigationType.toString() == "POP"){ + socket.emit("player quit") + } + } + + + useEffect(() => { const fetchUserInformation = async () => { try { @@ -96,6 +108,7 @@ function Play() { if (loggedIn){ login() setUserData(user) + socket.emit("join back game", user) } else{ loadImageAsync(defaultImg).then((blob) => { @@ -106,8 +119,20 @@ function Play() { } }) } + else{ + socket.emit("join back game", user) + } }, [isLoggedIn]); + const [goBackRoom, setGoBackRoom] = useState(-1) + + useEffect(() => { + socket.on("join back game", (room) => { + setGoBackRoom(room) + }) + }, []) + + const [room, setRoom] = useState(null); const navigate = useNavigate(); @@ -156,6 +181,10 @@ function Play() { } }, [room, navigate]); + const goBack = () => { + navigate("/lobby?room=" + goBackRoom) + } + const [showOverlay, setShowOverlay] = useState(false); @@ -246,7 +275,7 @@ function Play() { - + {goBackRoom != -1 && }