From d2b14cae26dac8aadd4b754399ed6e5f193bbe11 Mon Sep 17 00:00:00 2001 From: Atepir <sorghocharles8@gmail.com> Date: Sat, 22 Apr 2023 19:57:41 +0200 Subject: [PATCH] (feat: server) Ouagal - network events comm --- App/Assets/Scripts/Client.cs | 655 ++++++++++++++++++++--------------- 1 file changed, 368 insertions(+), 287 deletions(-) diff --git a/App/Assets/Scripts/Client.cs b/App/Assets/Scripts/Client.cs index 2bc8700ba..0fbd4c134 100644 --- a/App/Assets/Scripts/Client.cs +++ b/App/Assets/Scripts/Client.cs @@ -11,17 +11,21 @@ using System.Collections.Generic; using UnityEngine.SceneManagement; using System.Runtime.InteropServices; using UnityEditor; +using System.Collections; -public class Client : MonoBehaviour { +public class Client : MonoBehaviour +{ - public liaison liaison_test {get; set;} - public Socket clientSocket { - get{ + public liaison liaison_test { get; set; } + public Socket clientSocket + { + get + { return liaison.clientSocket; } } - + // StructureClientVersServeur [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct StructureClientVersServeur @@ -30,10 +34,10 @@ public class Client : MonoBehaviour { public int tag; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] public string pseudo; - + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] - public string newPseudo; - + public string newPseudo; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] public string passWord; @@ -47,11 +51,15 @@ public class Client : MonoBehaviour { public string code; public int id; + public int nbr; } + [SerializeField] + private Plateau plateauLocal; [StructLayout(LayoutKind.Sequential, Pack = 1)] - public struct PlayerProfile{ + public struct PlayerProfile + { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)] public string Pseudo; @@ -70,13 +78,14 @@ public class Client : MonoBehaviour { } - // structure contenant les donnes d'une partie + // structure contenant les donnes d'une partie [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct LobbyData { public int nbrJoueur; public int tag; public int gameId; + public int id_In_Game; } @@ -87,6 +96,23 @@ public class Client : MonoBehaviour { public int tag; public int gameId; public bool finished; + public int Joueurs; + public int timer; + public int idTour; + public Plateau plateau; + } + + + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct playerAction + { + public int id_Joueur; + public int tag; + public Pion pion; + public Case caseSpot; + public bool finished; + } // id du joueur dans la bdd @@ -155,13 +181,17 @@ public class Client : MonoBehaviour { private Sprite playerSprite; public static bool isPasswordShown = false; + //stock le nombre de joueur lors du lobby + public static int nbr; + + public static int id_Joueur_In_Game; + - // buffer pour les message a envoyé entrer depuis le terminal public byte[] buffer = new byte[1024]; //buffer receive esynchrone byte[] receiveBuffer = new byte[Marshal.SizeOf(typeof(LobbyData))]; - byte[] bufferbegin= new byte[Marshal.SizeOf(typeof(GameData))]; + byte[] bufferbegin = new byte[Marshal.SizeOf(typeof(GameData))]; @@ -171,23 +201,28 @@ public class Client : MonoBehaviour { /* ----------------------------------------fonctions------------------------------------------ */ - public void NextOption(){ + public void NextOption() + { selectedAvatar = selectedAvatar + 1; - if(selectedAvatar == avatars.Count){ - selectedAvatar =0; + if (selectedAvatar == avatars.Count) + { + selectedAvatar = 0; } sr.sprite = avatars[selectedAvatar]; } - public void BackOption(){ + public void BackOption() + { selectedAvatar = selectedAvatar - 1; - if(selectedAvatar < 0){ - selectedAvatar = avatars.Count -1; + if (selectedAvatar < 0) + { + selectedAvatar = avatars.Count - 1; } sr.sprite = avatars[selectedAvatar]; } - public void SetAvatar(){ + public void SetAvatar() + { PlayerPrefs.SetInt("SelectedAvatarIndex", selectedAvatar); PrefabUtility.SaveAsPrefabAsset(playerAvatar, "Assets/Prefabs/Av1.prefab"); playerSprite = selectedAvatarComp.GetComponent<SpriteRenderer>().sprite; @@ -197,10 +232,12 @@ public class Client : MonoBehaviour { //Afficher/Cacher le mot de passe - public void showPass(){ + public void showPass() + { isPasswordShown = !isPasswordShown; - if(isPasswordShown){ + if (isPasswordShown) + { passWord.contentType = TMP_InputField.ContentType.Standard; } @@ -208,12 +245,14 @@ public class Client : MonoBehaviour { } //Si l'utilisateur a oublié son mot de passe - public void forgetpass(){ + public void forgetpass() + { StructureClientVersServeur data = new StructureClientVersServeur(); data.tag = 7; data.email = email.text; - if(email.text == ""){ + if (email.text == "") + { AllFields.SetActive(true); } @@ -223,18 +262,20 @@ public class Client : MonoBehaviour { //Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); waitForgetpass(); - } + } - public void waitForgetpass(){ + public void waitForgetpass() + { byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string forget = Encoding.UTF8.GetString(buffer, 0, bytesReceived); - int forgetInt=int.Parse(forget); + int forgetInt = int.Parse(forget); - if(forgetInt == 1) SceneManager.LoadScene(0); + if (forgetInt == 1) SceneManager.LoadScene(0); - else{ + else + { // dire que le probleme Debug.Log(" mot de passe envoyer au client"); @@ -244,13 +285,15 @@ public class Client : MonoBehaviour { //Modifier le pseudo apres que le joueur soit connecté - public void ChangePseudo(){ + public void ChangePseudo() + { StructureClientVersServeur data = new StructureClientVersServeur(); data.tag = 12; data.id = idBdd; data.newPseudo = newPseudo.text; - if(newPseudo.text == ""){ + if (newPseudo.text == "") + { AllFields.SetActive(true); } @@ -260,41 +303,47 @@ public class Client : MonoBehaviour { //Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); waitChangePseudo(); - + } - public void waitChangePseudo(){ + public void waitChangePseudo() + { byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string change = Encoding.UTF8.GetString(buffer, 0, bytesReceived); - int changeInt=int.Parse(change); + int changeInt = int.Parse(change); + + if (changeInt == 1) + { - if(changeInt == 1) { - SceneManager.LoadScene(0); } //-1 pseudo exsite deja - else if(changeInt == -1 ){ + else if (changeInt == -1) + { Debug.Log("le pseudo existe deja"); retry.SetActive(true); } - else { + else + { Debug.Log("erreur lors modification"); } } //Si l'utilisateur veut modifier son mot de passe apres qu'il soit connecté - public void resetpass(){ + public void resetpass() + { StructureClientVersServeur data = new StructureClientVersServeur(); data.tag = 8; data.id = idBdd; data.passWord = passWord.text; data.newPassword = newpassWord.text; - if(passWord.text == "" || newpassWord.text == ""){ + if (passWord.text == "" || newpassWord.text == "") + { AllFields.SetActive(true); } @@ -306,16 +355,18 @@ public class Client : MonoBehaviour { waitResetpass(); } - public void waitResetpass(){ + public void waitResetpass() + { byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string reset = Encoding.UTF8.GetString(buffer, 0, bytesReceived); - int resetInt=int.Parse(reset); + int resetInt = int.Parse(reset); - if(resetInt == 1) SceneManager.LoadScene(0); + if (resetInt == 1) SceneManager.LoadScene(0); - else{ + else + { // dire que le probleme Debug.Log("le pass n'est pas bon"); AllFields.SetActive(false); @@ -326,7 +377,8 @@ public class Client : MonoBehaviour { //Si l'utilisateur veut supprimer son compte - public void suppCompte(){ + public void suppCompte() + { StructureClientVersServeur data = new StructureClientVersServeur(); data.tag = 9; data.id = idBdd; @@ -339,52 +391,61 @@ public class Client : MonoBehaviour { } - public void SuppPassCompte(){ + public void SuppPassCompte() + { Debug.Log(motDepasse); - if(passSuppField.text == ""){ + if (passSuppField.text == "") + { FieldEmptySupp.SetActive(true); } - if(motDepasse != passSuppField.text){ + if (motDepasse != passSuppField.text) + { FieldEmptySupp.SetActive(false); PassIncorrectSupp.SetActive(true); } - else { + else + { SuppScene.SetActive(false); validateSupression.SetActive(true); } - + } - public void waitSuppCompte(){ + public void waitSuppCompte() + { byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); - string supp = Encoding.UTF8.GetString(buffer,0,bytesReceived); + string supp = Encoding.UTF8.GetString(buffer, 0, bytesReceived); int forgetInt = int.Parse(supp); - if(forgetInt == 1) { + if (forgetInt == 1) + { Debug.Log("Le compte est suprrimé"); SceneManager.LoadScene(0); } - else{ + else + { Debug.Log("erreur lors suppression"); compteSuprr.SetActive(true); } } - //lorsque l'utilisateur click sur ce connecter - public void onLoginSubmit(){ + //lorsque l'utilisateur click sur ce connecter + public void onLoginSubmit() + { - StructureClientVersServeur data= new StructureClientVersServeur() ; - data.tag=2; - data.pseudo=pseudo.text; - data.passWord=passWord.text; + StructureClientVersServeur data = new StructureClientVersServeur(); + data.tag = 2; + data.pseudo = pseudo.text; + data.passWord = passWord.text; - motDepasse=data.passWord; - userName=data.pseudo; + motDepasse = data.passWord; + userName = data.pseudo; - if(pseudo.text == "" || passWord.text == ""){ + if (pseudo.text == "" || passWord.text == "") + { Debug.Log("Field Empty!"); retry.SetActive(false); AllFields.SetActive(true); @@ -393,39 +454,42 @@ public class Client : MonoBehaviour { // Convertir la structure en tableau de bytes string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + byte[] bytes = Encoding.UTF8.GetBytes(json); // Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); - + validationConnection(); } // apres le click sur se connecter attendre la validation de ces données - public void validationConnection(){ - + public void validationConnection() + { + byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string connection = Encoding.UTF8.GetString(buffer, 0, bytesReceived); // si la connection est accepté diriger vers la page principale - int connectionInt=int.Parse(connection); - if(connectionInt > 0){ + int connectionInt = int.Parse(connection); + if (connectionInt > 0) + { idBdd = connectionInt; // changer de frame Debug.Log("les données sont bons ton id " + connection); Debug.Log("valueru conn :" + connectionInt); + byte[] bytes = new byte[Marshal.SizeOf(typeof(PlayerProfile))]; int bytesRec = clientSocket.Receive(bytes); - string json = Encoding.UTF8.GetString(bytes,0,bytesRec); + string json = Encoding.UTF8.GetString(bytes, 0, bytesRec); PlayerProfile playerProfile = JsonUtility.FromJson<PlayerProfile>(json); - - PlayerPrefs.SetString("Username",playerProfile.Pseudo); - PlayerPrefs.SetString("nbMatch",playerProfile.nbMatch); - PlayerPrefs.SetString("nbVictoire",playerProfile.nbVictoire); + + PlayerPrefs.SetString("Username", playerProfile.Pseudo); + PlayerPrefs.SetString("nbMatch", playerProfile.nbMatch); + PlayerPrefs.SetString("nbVictoire", playerProfile.nbVictoire); Debug.Log("Avatar" + playerProfile.Avatar); //byte[] imageBytes = System.Convert.FromBase64String(playerProfile.Avatar); @@ -442,7 +506,8 @@ public class Client : MonoBehaviour { SceneManager.LoadScene(3); } // si non erreur - else{ + else + { switch (connectionInt) { case -1: @@ -451,8 +516,8 @@ public class Client : MonoBehaviour { login_pwd_Mauvais.SetActive(false); dejaconn.SetActive(true); break; - // attendre si le code est bon ou pas et changer la scene avec - + // attendre si le code est bon ou pas et changer la scene avec + default: Debug.Log("pseudo/mot de passe est mauvais!"); dejaconn.SetActive(false); @@ -460,14 +525,15 @@ public class Client : MonoBehaviour { pseudo.textComponent.color = Color.red; passWord.textComponent.color = Color.red; break; - + } } } - + //Récuperer les données personnelles et les statistiques du joueur - public void getProfil(){ + public void getProfil() + { string username1 = PlayerPrefs.GetString("Username"); usernameText.SetText(username1); @@ -492,17 +558,19 @@ public class Client : MonoBehaviour { } //lorsque l'utilisateur click sur s'inscrire - public void onSignup(){ - + public void onSignup() + { + Debug.Log("active inscir"); - StructureClientVersServeur data= new StructureClientVersServeur() ; - data.tag=1; - data.pseudo=pseudo.text; - data.email=email.text; - data.passWord=passWord.text; - - // Convertir la structure en tableau de bytes - if(pseudo.text == "" || email.text == "" || passWord.text == ""){ + StructureClientVersServeur data = new StructureClientVersServeur(); + data.tag = 1; + data.pseudo = pseudo.text; + data.email = email.text; + data.passWord = passWord.text; + + // Convertir la structure en tableau de bytes + if (pseudo.text == "" || email.text == "" || passWord.text == "") + { Debug.Log("Field Empty!"); retry.SetActive(false); AllFields.SetActive(true); @@ -513,7 +581,7 @@ public class Client : MonoBehaviour { Debug.Log(data.email); string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + byte[] bytes = Encoding.UTF8.GetBytes(json); // Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); @@ -524,13 +592,14 @@ public class Client : MonoBehaviour { } //apres le click sur s'inscrire attendre la validation du serveur - public void validationInscription(){ + public void validationInscription() + { byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string inscript = Encoding.UTF8.GetString(buffer, 0, bytesReceived); - int inscriptInt=int.Parse(inscript); + int inscriptInt = int.Parse(inscript); switch (inscriptInt) { @@ -541,8 +610,8 @@ public class Client : MonoBehaviour { // vers page de code SceneManager.LoadScene(5); break; - // attendre si le code est bon ou pas et changer la scene avec - + // attendre si le code est bon ou pas et changer la scene avec + case 10: // le pseudo est deja use pseudoExist.SetActive(true); @@ -558,235 +627,241 @@ public class Client : MonoBehaviour { // mail deja use emailExist.SetActive(true); email.textComponent.color = Color.red; - break; + break; } - + } //lorsque l'utilisateur click sur jouer - public void onPlay(){ + public void onPlay() + { + leaveTheLobby = false; Debug.Log("active"); - StructureClientVersServeur data= new StructureClientVersServeur() ; - data.tag=3; - data.id=idBdd; + StructureClientVersServeur data = new StructureClientVersServeur(); + data.tag = 3; + data.id = idBdd; data.pseudo = usernameText.text; - - // Convertir la structure en tableau de bytes + + // Convertir la structure en tableau de bytes string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + byte[] bytes = Encoding.UTF8.GetBytes(json); // Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); - //waitPlay(); - waitGame = true; - - + StartCoroutine(WaitPlayCoroutine()); } - public void onLeaveLobby(){ - Debug.Log("je veux quittez le lobby "); - StructureClientVersServeur data= new StructureClientVersServeur() ; - data.tag=11; - - // Convertir la structure en tableau de bytes - string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + public bool leaveTheLobby = false; + public IEnumerator WaitPlayCoroutine() + { + LobbyData lobbyGame = new LobbyData(); - // Envoyer les données au serveur - int bytesSent = clientSocket.Send(bytes); + while (!leaveTheLobby) + { + if (clientSocket.Poll(0, SelectMode.SelectRead)) + { + // Récupérer le json + byte[] bytesLobby = new byte[Marshal.SizeOf(typeof(LobbyData))]; + int bytesRec; + StringBuilder data = new StringBuilder(); - } + do + { + bytesRec = clientSocket.Receive(bytesLobby); + data.Append(Encoding.ASCII.GetString(bytesLobby, 0, bytesRec)); + yield return null; // Attendre une frame pour éviter de bloquer le thread principal + } while (clientSocket.Available > 0); - private void Update() - { - if (waitGame){ - waitPlay(); - } - - } + string jsonLobby = data.ToString(); + Debug.Log("Le json est :" + jsonLobby + " bytes reçu " + bytesRec); - public void waitPlay(){ - LobbyData lobbyGame= new LobbyData(); + lobbyGame = JsonUtility.FromJson<LobbyData>(jsonLobby); + int nbrJoueur = lobbyGame.nbrJoueur; + nbr = lobbyGame.nbrJoueur; + nbJoueur.text = nbrJoueur.ToString(); - // recupere le json - byte[] bytesLobby = new byte[Marshal.SizeOf(typeof(LobbyData))]; - int bytesRec; - StringBuilder data = new StringBuilder(); + // Chercher à savoir s'il faut jouer ou attendre + switch (lobbyGame.tag) + { + case 1: + // Charger la scène souhaitée + loadingLobby.SetActive(false); + loadingLobby.SetActive(true); + Debug.Log("Le jso " + jsonLobby); - do { - bytesRec = clientSocket.Receive(bytesLobby); - data.Append(Encoding.ASCII.GetString(bytesLobby, 0, bytesRec)); - } while (clientSocket.Available > 0); - string jsonLobby = data.ToString(); - Debug.Log(" le json est :"+jsonLobby+"bytes recu "+bytesRec); + break; + case 0: + leaveTheLobby = false; + id_Joueur_In_Game = lobbyGame.id_In_Game; + StartCoroutine(commManager()); - lobbyGame = JsonUtility.FromJson<LobbyData>(jsonLobby); - int nbr = lobbyGame.nbrJoueur; - nbJoueur.text= nbr.ToString(); + // Faire quelque chose pour le tag 0 + // aller vers une deuxieme coroutine pour la gestion des envoi et reception au cours d'une partie - // chercher a savoir si il faut jouer ou attendre - switch (lobbyGame.tag) { - - case 1 : - - Debug.Log("NUMBER"+ nbr); - Debug.Log("attente des autres joueurs"); - - clientSocket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, new AsyncCallback(waitGameStart), null); - break; + break; - case 0 : + default: + Debug.Log("On est dans le default, il y a eu un mauvais tag reçu"); - // TO DO - // charger la scene avec les 4 avatars ( les avatar seront dans avatarJsonList conetenu dans lobbyGame - //et dans 5 seconde la game va commencer - // on attendre de recevoir le pleateu faire une autre fonction assynchrone pour attendre - SceneManager.LoadScene(4); - clientSocket.BeginReceive(bufferbegin, 0, bufferbegin.Length, SocketFlags.None, new AsyncCallback(beginGame), null); - break; + break; + } + } - default : - Debug.Log("on est dans le defaul il y a eu un mauvais tag recu"); - break; + yield return null; // Attendre une frame avant de vérifier à nouveau } - - } - public void beginGame(IAsyncResult result){ - Debug.Log("la seconde attente"); + public bool endOfGame = false; + public IEnumerator commManager() + { + GameData onGame = new GameData(); - try + while (!endOfGame) { - // Récupération des données reçues - - int bytesRead; - StringBuilder data = new StringBuilder(); - bytesRead = clientSocket.EndReceive(result); - data.Append(Encoding.ASCII.GetString(bufferbegin, 0, bytesRead)); - - do { - bytesRead = clientSocket.Receive(bufferbegin); - data.Append(Encoding.ASCII.GetString(bufferbegin, 0, bytesRead)); - - } while (clientSocket.Available > 0); - - if (bytesRead > 0) + if (clientSocket.Poll(0, SelectMode.SelectRead)) { - // recuperer la structure qui contient etat du jeu - GameData gameStructure= new GameData(); - // recupere le json - string json = data.ToString(); - Debug.Log("le json du beginGame est :"+json); + // Récupérer le json + byte[] bytesGame = new byte[Marshal.SizeOf(typeof(GameData))]; + int bytesRec; + StringBuilder data = new StringBuilder(); - gameStructure = JsonUtility.FromJson<GameData>(json); + do + { + bytesRec = clientSocket.Receive(bytesGame); + data.Append(Encoding.ASCII.GetString(bytesGame, 0, bytesRec)); + yield return null; // Attendre une frame pour éviter de bloquer le thread principal + } while (clientSocket.Available > 0); - // afficher le plateau et maybe faire le traitement pour recuperer les input - - if ( !gameStructure.finished ) clientSocket.BeginReceive(bufferbegin, 0, bufferbegin.Length, SocketFlags.None, new AsyncCallback(beginGame), null); + string jsonGame = data.ToString(); + Debug.Log("Le json est :" + jsonGame + " bytes reçu " + bytesRec); - else{ - // afficher la scene de score - } + onGame = JsonUtility.FromJson<GameData>(jsonGame); - } + // Chercher à savoir s'il faut jouer ou attendre + switch (onGame.tag) + { + case 22: + // reception d'un plateau a afficher + // detecter la fin d'une partie et arreter la boucle + if (onGame.finished) endOfGame = true; - // Lancement d'une nouvelle opération de receive non bloquant pour attendre les etats jusqu'a la fin de la game - - } - catch (Exception e) - { - Debug.Log("begin game Receive error: " + e.Message); - } - - } + break; - public void waitGameStart(IAsyncResult result){ - - Debug.Log("j'attend les nouvelles infos "); - try - { - // Récupération des données reçues - int bytesRead; - StringBuilder data = new StringBuilder(); - bytesRead = clientSocket.Receive(receiveBuffer); - data.Append(Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead)); + case 21: + // pawntimer + // detecter la fin d'une partie et arreter la boucle + if (onGame.finished) endOfGame = true; - do { - bytesRead = clientSocket.Receive(receiveBuffer); - data.Append(Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead)); - } while (clientSocket.Available > 0); - if (bytesRead > 0) - { - // Traitement des données reçues - LobbyData lobbyGame= new LobbyData(); - // recupere le json - string json = data.ToString(); - Debug.Log("le json du WaitGame start est "+json); - lobbyGame = JsonUtility.FromJson<LobbyData>(json); - - switch (lobbyGame.tag) { - case 0: - // debut de la partie - clientSocket.BeginReceive(bufferbegin, 0, bufferbegin.Length, SocketFlags.None, new AsyncCallback(beginGame), null); break; - case 1: - // affichage de scenen avec le nombre d'avatr donne - int nbr = lobbyGame.nbrJoueur; - nbJoueur.text= nbr.ToString(); - SceneManager.LoadScene(4); + case 20: + //dicetimer + // detecter la fin d'une partie et arreter la boucle + if (onGame.finished) endOfGame = true; + - // Lancement d'une nouvelle opération de receive non bloquant - clientSocket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, new AsyncCallback(waitGameStart), null); break; - default : - + + default: + Debug.Log("On est dans le default, il y a eu un mauvais tag reçu"); + break; } - } + + yield return null; // Attendre une frame avant de vérifier à nouveau } - catch (Exception e) - { - Debug.Log("wait game start Receive error: " + e.Message); - } -} + } + + // TODO stocker l'id du joueur lors d'une partie + public void onDiceclicked() + { + + // structure pour les actions du client sur le plateau + playerAction action = new playerAction(); + action.tag = 23; + action.id_Joueur = id_Joueur_In_Game; + + string json = JsonUtility.ToJson(action); + byte[] bytesClicked = Encoding.UTF8.GetBytes(json); + clientSocket.Send(bytesClicked); - public void onDisconnection(){ + } + + public void onPionMoved(Pion pion, Case case_Du_pion) + { - StructureClientVersServeur data= new StructureClientVersServeur(); + // structure pour les actions du client sur le plateau + playerAction action = new playerAction(); + action.tag = 24; + action.pion = pion; + action.caseSpot = case_Du_pion; + //TO DO recuperer le id du joueur lorsque la partie commence ps: envoyé par le serveur + action.id_Joueur = id_Joueur_In_Game; - data.tag=4; - data.id=idBdd; + string json = JsonUtility.ToJson(action); + byte[] bytesPionMoved = Encoding.UTF8.GetBytes(json); + clientSocket.Send(bytesPionMoved); + + + } + + + public void onLeaveLobby() + { + leaveTheLobby = true; + + Debug.Log("je veux quittez le lobby "); + StructureClientVersServeur data = new StructureClientVersServeur(); + data.tag = 11; + data.nbr = nbr; + + // Convertir la structure en tableau de bytes + string json = JsonUtility.ToJson(data); + byte[] bytes = Encoding.UTF8.GetBytes(json); + + // Envoyer les données au serveur + int bytesSent = clientSocket.Send(bytes); + + } + + public void onDisconnection() + { + + StructureClientVersServeur data = new StructureClientVersServeur(); + + data.tag = 4; + data.id = idBdd; // Convertir la structure en tableau de bytes - Debug.Log("valeur: "+data.id); + Debug.Log("valeur: " + data.id); string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + byte[] bytes = Encoding.UTF8.GetBytes(json); // Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); waitDisconnection(); } - public void waitDisconnection(){ + public void waitDisconnection() + { // chercher a savoir si il faut jouer ou attendre byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string wait = Encoding.UTF8.GetString(buffer, 0, bytesReceived); - int waitInt=int.Parse(wait); + int waitInt = int.Parse(wait); - if (waitInt == 1){ + if (waitInt == 1) + { Debug.Log("t'es deconnecté"); SceneManager.LoadScene(0); @@ -797,62 +872,68 @@ public class Client : MonoBehaviour { } - public void onCodeSubmit(){ + public void onCodeSubmit() + { Debug.Log("active code"); string code = validation.text; - if(validation.text == ""){ + if (validation.text == "") + { AllFields.SetActive(true); return; } Debug.Log(code); - byte[] bytes =Encoding.UTF8.GetBytes(code); + byte[] bytes = Encoding.UTF8.GetBytes(code); // Envoyer les données au serveur int bytesSent = clientSocket.Send(bytes); waitValidation(); } - - public void waitValidation(){ - byte[] buffer = new byte[1024]; - int bytesReceived = clientSocket.Receive(buffer); - string code = Encoding.UTF8.GetString(buffer, 0, bytesReceived); + public void waitValidation() + { + + byte[] buffer = new byte[1024]; + int bytesReceived = clientSocket.Receive(buffer); + string code = Encoding.UTF8.GetString(buffer, 0, bytesReceived); + + Debug.Log("on est la " + code); + + int codeInt = int.Parse(code); + Debug.Log("code int : " + codeInt); + - Debug.Log("on est la " +code); + if (codeInt == 1) + { + Debug.Log("inscription réussi"); + SceneManager.LoadScene(0); + } + // si mauvais code de verification erreur + else + { + // erreur - int codeInt=int.Parse(code); - Debug.Log("code int : " +codeInt); - - - if(codeInt == 1){ - Debug.Log("inscription réussi"); - SceneManager.LoadScene(0); - } - // si mauvais code de verification erreur - else{ - // erreur - - Debug.Log("on est else " +code); - AllFields.SetActive(false); - retry.SetActive(true); + Debug.Log("on est else " + code); + AllFields.SetActive(false); + retry.SetActive(true); - // champ de code de validation - validation.text =""; - } + // champ de code de validation + validation.text = ""; + } } - public void onShutDown(){ + public void onShutDown() + { Debug.Log("deconnection commencer"); - StructureClientVersServeur data= new StructureClientVersServeur() ; - data.tag=5; + StructureClientVersServeur data = new StructureClientVersServeur(); + data.tag = 5; // conversion en bytes string json = JsonUtility.ToJson(data); - byte[] bytes =Encoding.UTF8.GetBytes(json); + byte[] bytes = Encoding.UTF8.GetBytes(json); //envoi au serveur clientSocket.Send(bytes); @@ -864,11 +945,11 @@ public class Client : MonoBehaviour { // attndre que tous les paquets soient envoyés ou recu clientSocket.ReceiveTimeout = 100; clientSocket.SendTimeout = 100; - + clientSocket.Close(); } - - Debug.Log("deconnection terminer"); + + Debug.Log("deconnection terminer"); // Fermer l'application Application.Quit(); -- GitLab