/////////////////////////////////////////////////////////////////////////////// // // TURNO DEL JUGADOR // /////////////////////////////////////////////////////////////////////////////// // Gestión del evento de turno del socket IEnumerator turno(string jugador) { WaitingTurno.SetActive(false); //Need debug checkColorPlayername(Player1, jugador, "turno"); checkColorPlayername(Player2, jugador, "turno"); checkColorPlayername(Player3, jugador, "turno"); checkColorPlayername(Player4, jugador, "turno"); checkColorPlayername(Player5, jugador, "turno"); checkColorPlayername(Player6, jugador, "turno"); //Our turn if (jugador.Equals(UserDataScript.getInfo("username"))) { try { DiceGO.SetActive(true); Dice.interactable = true; DiceAnimation.Play(); //Lanzar animación } catch (Exception e) { Debug.Log(e); } } yield return(null); }
IEnumerator setPropio() { //Jugador(string nombre, string banner, string avatar, string ficha, int posicion, string[] quesitos) string nombre = UserDataScript.getInfo("username"); string banner = UserDataScript.getInfo("banner"); string avatar = UserDataScript.getInfo("avatar"); string ficha = UserDataScript.getInfo("token"); PlayersDataScript.Jugador jugador = new PlayersDataScript.Jugador(nombre, banner, avatar, ficha, 777, new string[] { }); PlayersDataScript.nuevoJugador(jugador); GameObject usuarioGO = new GameObject(nombre); usuarioGO.transform.SetParent(Usuarios.transform); RectTransform usuarioRT = usuarioGO.AddComponent <RectTransform>(); usuarioRT.sizeDelta = new Vector2(450, 51); usuarioRT.localScale = new Vector3(1, 1, 1); Text usuarioText = usuarioGO.AddComponent <Text>(); usuarioText.text = nombre; usuarioText.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font; usuarioText.alignment = TextAnchor.MiddleLeft; usuarioText.fontSize = 36; usuarioText.fontStyle = FontStyle.Bold; jugadores++; yield return(null); }
//Instanciar los jugadores de la partida private void setPlayersAtStart() { for (int i = 0; i < 6; i++) { Players[i].SetActive(i < PlayersDataScript.jugadores.Count); Tokens[i].SetActive(i < PlayersDataScript.jugadores.Count); if (i < PlayersDataScript.jugadores.Count) { Players[i].name = PlayersDataScript.jugadores[i].nombre; Players[i].GetComponentInChildren <Text>().text = PlayersDataScript.jugadores[i].nombre; Players[i].GetComponentsInChildren <Image>(true)[0].sprite = Resources.Load <Sprite>("Avatar/" + PlayersDataScript.jugadores[i].avatar); Players[i].GetComponentsInChildren <Image>(true)[1].sprite = Resources.Load <Sprite>("Token/" + PlayersDataScript.jugadores[i].ficha); Tokens[i].name = PlayersDataScript.jugadores[i].nombre; Tokens[i].GetComponent <Image>().sprite = Resources.Load <Sprite>("Token/" + PlayersDataScript.jugadores[i].ficha); foreach (string img in PlayersDataScript.jugadores[i].quesitos) { int idx = Array.FindIndex(categories, (c) => { return(c.Equals(img)); }); Players[i].GetComponentsInChildren <Image>(true)[3 + idx].gameObject.SetActive(true); } setTokenInPosition(Tokens[i], PlayersDataScript.jugadores[i].posicion); //Verificamos que ficha es la nuestra y guardamos referencia if (Players[i].name == UserDataScript.getInfo("username")) { QuestionBehaviourScript.myPlayer = Players[i]; myPlayer = Players[i]; myToken = Tokens[i]; } } } StartCoroutine(turno(PlayersDataScript.turno)); }
private void addCoin() { if (!UserDataScript.getInfo("username").StartsWith("Guest_")) { StartCoroutine(AddCoinRequest(UserDataScript.getInfo("token"))); } }
public static bool Start(Action fnConexion, Action fnEnd, Dictionary <string, Action <object> > handlers) { if (handlers.Count == 0) { return(false); } Debug.Log("Comienza initSocketio()"); try { IO.Options opciones = new IO.Options(); opciones.ExtraHeaders.Add("jwt", UserDataScript.getInfo("token")); opciones.ExtraHeaders.Add("operacion", op); foreach (KeyValuePair <string, string> entry in args) { opciones.ExtraHeaders.Add(entry.Key, entry.Value); } socket = IO.Socket(ENDPOINT, opciones); foreach (KeyValuePair <string, Action <object> > entry in handlers) { socket.On(entry.Key, entry.Value); } socket.On(QSocket.EVENT_DISCONNECT, (reason) => { Debug.Log("Disconnected: " + reason + " \n" + Environment.StackTrace); PlayersDataScript.eliminarPartida(); fnEnd(); }); socket.On(QSocket.EVENT_RECONNECT, () => { Debug.Log("Reconnected"); }); socket.On(QSocket.EVENT_CONNECT, () => { Debug.Log("Connected"); fnConexion(); }); }catch (Exception e) { Debug.Log("Exception: " + e); } return(true); }
//Temporal private void addCoin() { if (!UserDataScript.getInfo("username").StartsWith("Guest_")) { StartCoroutine(AddCoinRequest(UserDataScript.getInfo("token"), UnityEngine.Random.Range(1, 21))); } }
void Update() { Coins.text = "" + UserDataScript.getCoins(); BannerImage.sprite = Resources.Load <Sprite>("Banner/" + UserDataScript.getInfo("banner")); AvatarImage.sprite = Resources.Load <Sprite>("Avatar/" + UserDataScript.getInfo("avatar")); FichaImage.sprite = Resources.Load <Sprite>("Token/" + UserDataScript.getInfo("ficha")); if (!string.IsNullOrEmpty(RepasswordInput.text) & RepasswordInput.text != PasswordInput.text) { RepasswordImage.enabled = true; } else { RepasswordImage.enabled = false; } if (string.IsNullOrEmpty(PasswordInput.text) | string.IsNullOrEmpty(RepasswordInput.text) | RepasswordInput.text != PasswordInput.text) { ChangePasswordButton.interactable = false; } else { ChangePasswordButton.interactable = true; } }
// Start is called before the first frame update void Start() { ManageButton.onClick.AddListener(ManageButtonOnClick); ReturnButton.onClick.AddListener(ReturnButtonOnClick); ShopButton.onClick.AddListener(ShopButtonOnClick); CloseSessionButton.onClick.AddListener(CloseSessionButtonOnClick); ChangePasswordButton.onClick.AddListener(ChangePasswordButtonOnClick); DeleteProfileButton.onClick.AddListener(DeleteProfileButtonOnClick); //Update user info StartCoroutine(ProfileRequest(UserDataScript.getInfo("token"))); //Show new user info InfoText.text = "Usuario: " + UserDataScript.getInfo("username") + "\n" + "Email: " + UserDataScript.getInfo("email") + "\n\n" + "Pregunta: " + UserDataScript.getInfo("question") + "\n" + "Respuesta: " + UserDataScript.getInfo("answer") + "\n\n" + "Partidas jugadas: " + UserDataScript.getPlayed() + "\n" + "Partidas ganadas:" + UserDataScript.getWins() + "\n"; Username.text = UserDataScript.getInfo("username"); ManageCanvas.SetActive(false); }
void DeleteProfileButtonOnClick() { //SceneManager.UnloadSceneAsync("Profile Scene"); //SceneManager.LoadScene("Login Scene", LoadSceneMode.Single); //ConfirmDataScript.setConfirmText("¿Estas seguro de eliminar tu cuenta?"); //SceneManager.LoadScene("Confirm Scene", LoadSceneMode.Additive); StartCoroutine(DeleteProfileRequest(UserDataScript.getInfo("token"))); }
IEnumerator cambioLider(JObject data) { JValue nuevo = (JValue)data.Property("nuevo").Value; string nuevoString = (string)nuevo.Value; JValue antiguo = (JValue)data.Property("antiguo").Value; string antiguoString = (string)antiguo.Value; if (nuevoString.Equals(UserDataScript.getInfo("username"))) { setLider(true); } yield return(salidaUsuario(antiguoString)); }
private IEnumerator checkUserReconnection() { UnityWebRequest requestPartida = UnityWebRequest.Get("https://unitrivia.herokuapp.com/api/partida/reconexion"); requestPartida.SetRequestHeader("jwt", UserDataScript.getInfo("token")); yield return(requestPartida.SendWebRequest()); bool reconexion = requestPartida.downloadHandler.text != ""; Debug.Log(requestPartida.downloadHandler.text); ReconnectButton.gameObject.SetActive(reconexion); RandomGameButton.gameObject.SetActive(!reconexion); JoinGameButton.gameObject.SetActive(!reconexion); CreateGameButton.gameObject.SetActive(!reconexion); }
IEnumerator findDelJuego(string jugador) { winner.text = jugador; if (jugador.Equals(UserDataScript.getInfo("username"))) { endgameImage.sprite = Resources.Load <Sprite>("victory"); } else { endgameImage.sprite = Resources.Load <Sprite>("defeat"); } endgame.SetActive(true); yield return(null); }
// Start is called before the first frame update void Start() { //Desactivamos botones hasta gestionar la reconexión si hay JoinGameCanvas.enabled = false; ReconnectButton.gameObject.SetActive(false); RandomGameButton.gameObject.SetActive(false); JoinGameButton.gameObject.SetActive(false); CreateGameButton.gameObject.SetActive(false); //Add Listeners RandomGameButton.onClick.AddListener(RandomGameOnClick); JoinGameButton.onClick.AddListener(JoinGameOnClick); CreateGameButton.onClick.AddListener(CreateGameOnClick); ReconnectButton.onClick.AddListener(ReconnectOnClick); InputIDButton.onClick.AddListener(InputIDButtonOnClick); ReturnButton.onClick.AddListener(ReturnButtonOnClick); ProfileButton.onClick.AddListener(ProfileButtonOnClick); LoginButton.onClick.AddListener(LoginButtonOnClick); OptionsButton.onClick.AddListener(OptionsButtonOnClick); //UserInfo Username.text = UserDataScript.getInfo("username"); if (UserDataScript.getInfo("username").StartsWith("Guest_")) { Resources.Load <Sprite>("Avatar/avatar0"); ProfileButton.gameObject.SetActive(false); } else { Resources.Load <Sprite>("Avatar/" + PlayerPrefs.GetString("avatar")); LoginButton.gameObject.SetActive(false); } StartCoroutine(checkUserReconnection()); IdentificadorInput.onValueChanged.AddListener((id) => { InputIDButton.interactable = !string.IsNullOrEmpty(id) && id.Length == 5; }); }
void checkActualItem() { if (UserDataScript.isItem(objectName + index)) { BuyButton.interactable = false; BuyButton.GetComponentInChildren <Text>().text = "EN POSESIÓN"; BuyButton.GetComponentInChildren <Text>().color = Color.white; if (UserDataScript.getInfo(objectName).Equals(objectName + index)) { ActiveButton.interactable = false; ActiveButton.GetComponentInChildren <Text>().text = "ACTIVADO"; } else { ActiveButton.interactable = true; ActiveButton.GetComponentInChildren <Text>().text = "ACTIVAR"; } } else { if (UserDataScript.getCoins() < 100) { BuyButton.interactable = false; BuyButton.GetComponentInChildren <Text>().text = "COMPRAR|100c"; BuyButton.GetComponentInChildren <Text>().color = Color.red; } else { BuyButton.interactable = true; BuyButton.GetComponentInChildren <Text>().text = "COMPRAR|100c"; BuyButton.GetComponentInChildren <Text>().color = Color.white; } ActiveButton.interactable = false; ActiveButton.GetComponentInChildren <Text>().text = "ACTIVAR"; } }
//Request to the server for Login private IEnumerator BuyRequest(string item) { UnityWebRequest requestBuy = null; requestBuy = UnityWebRequest.Post("https://unitrivia.herokuapp.com/api/tienda/comprar", ""); requestBuy.SetRequestHeader("nombre", item); requestBuy.SetRequestHeader("jwt", UserDataScript.getInfo("token")); yield return(requestBuy.SendWebRequest()); Debug.Log("ResponseCode: " + requestBuy.responseCode); if (requestBuy.result == UnityWebRequest.Result.ConnectionError) { Debug.Log("ERROR CONNECTION ACTIVESHOP:" + requestBuy.result); ErrorDataScript.setErrorText("Error de conexión"); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); } else if (requestBuy.responseCode != 200) { Debug.Log("ERROR ACTIVESHOP:" + requestBuy.downloadHandler.text); ErrorReturn result = ErrorReturn.CreateFromJSON(requestBuy.downloadHandler.text); ErrorDataScript.setErrorText(result.message); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); } else { Debug.Log("EXITO ACTIVESHOP:" + requestBuy.downloadHandler.text); SoundManager.PlayBuySound(); UserDataScript.addItem(item); UserDataScript.removeCoins(100); checkActualItem(); } }
/////////////////////////////////////////////////////////////////////////////// // // GESTION DEL CHAT // /////////////////////////////////////////////////////////////////////////////// //Cuando se pulsa el botón para enviar un mensaje void SendMsg() { chatLog.text = UserDataScript.getInfo("username") + ": " + msg.text + "\n" + chatLog.text; SocketioHandler.socket.Emit("mensaje", msg.text); msg.text = ""; }
void Update() { UserAvatar.sprite = Resources.Load <Sprite>("Avatar/" + UserDataScript.getInfo("avatar")); Coins.text = "" + UserDataScript.getCoins(); }
void ChangePasswordButtonOnClick() { StartCoroutine(ChangePasswordRequest(UserDataScript.getInfo("username"), UserDataScript.getInfo("answer"), PasswordInput.text)); }
//Request to the server for Login private IEnumerator ActiveRequest(string item, string type) { UnityWebRequest requestActive = null; switch (type) { case "avatar": requestActive = UnityWebRequest.Post("https://unitrivia.herokuapp.com/api/profile/modify/avatar", ""); requestActive.SetRequestHeader("idavatar", item); break; case "banner": requestActive = UnityWebRequest.Post("https://unitrivia.herokuapp.com/api/profile/modify/banner", ""); requestActive.SetRequestHeader("idbanner", item); break; case "ficha": requestActive = UnityWebRequest.Post("https://unitrivia.herokuapp.com/api/profile/modify/formFicha", ""); requestActive.SetRequestHeader("idformficha", item); break; default: ErrorDataScript.setErrorText("Error inesperado"); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); break; } if (requestActive != null) { requestActive.SetRequestHeader("jwt", UserDataScript.getInfo("token")); yield return(requestActive.SendWebRequest()); Debug.Log("ResponseCode: " + requestActive.responseCode); if (requestActive.result == UnityWebRequest.Result.ConnectionError) { Debug.Log("ERROR CONNECTION ACTIVESHOP:" + requestActive.result); ErrorDataScript.setErrorText("Error de conexión"); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); } else if (requestActive.responseCode != 200) { Debug.Log("ERROR ACTIVESHOP:" + requestActive.downloadHandler.text); ErrorReturn result = ErrorReturn.CreateFromJSON(requestActive.downloadHandler.text); ErrorDataScript.setErrorText(result.message); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); } else { Debug.Log("EXITO ACTIVESHOP:" + requestActive.downloadHandler.text); switch (type) { case "avatar": UserDataScript.setInfo("avatar", item); break; case "banner": UserDataScript.setInfo("banner", item); break; case "ficha": UserDataScript.setInfo("ficha", item); break; default: ErrorDataScript.setErrorText("Error. Vuelve a intentarlo."); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); break; } checkActualItem(); } } else { ErrorDataScript.setErrorText("Objeto no reconocido"); ErrorDataScript.setButtonMode(1); SceneManager.LoadScene("Error Scene", LoadSceneMode.Additive); } }
IEnumerator posiblesJugadasCallback(JObject jugadas) { JValue resJV = (JValue)jugadas.Property("res").Value; string res = (string)resJV.Value; if (res.Equals("ok")) { JArray movimientos = (JArray)jugadas.Property("info").Value; foreach (JToken j in movimientos) { // j = { // casilla: { // num: <integer>, // categoria: <string>, // tipo: <string> // }, // pregunta: { // categoria: <string>, // pregunta: <string>, // resp_c: <string>, // resps_inc: <Array<string>>, // _id: <string>, // } // } JObject tmp = (JObject)j; JObject casillaJO = (JObject)tmp.Property("casilla").Value; int casilla = (int)casillaJO.Property("num").Value; string tipo = (string)casillaJO.Property("tipo").Value; if (tipo.Equals("Dado")) { BoardButtons.transform.Find("BoardButton (" + casilla + ")").GetComponent <Button>().onClick.AddListener(() => { hideBoardButtons(); setTokenInPosition(myToken, casilla); SendJugada(casilla, "", false, true); StartCoroutine(turno(UserDataScript.getInfo("username"))); foreach (Button b in BoardButtons.GetComponentsInChildren <Button>(true)) { b.onClick.RemoveAllListeners(); } }); } else { JObject preguntaJO = (JObject)tmp.Property("pregunta").Value; string categoria = (string)preguntaJO.Property("categoria").Value; string question = WebUtility.HtmlDecode((string)preguntaJO.Property("pregunta").Value); string resp_c = WebUtility.HtmlDecode((string)preguntaJO.Property("resp_c").Value); JArray resp_incJA = (JArray)preguntaJO.Property("resps_inc").Value; List <string> resp_inc = new List <string>(); foreach (JToken r in resp_incJA) { resp_inc.Add(WebUtility.HtmlDecode((string)r)); } Button button = BoardButtons.transform.Find("BoardButton (" + casilla + ")").GetComponent <Button>(); button.onClick.AddListener(() => { hideBoardButtons(); setTokenInPosition(myToken, casilla); newQuestion(tipo.Equals("Quesito"), categoria, question, resp_c, resp_inc, casilla); Debug.Log("Pregunta: " + question + "| Respuesta = " + resp_c); foreach (Button b in BoardButtons.GetComponentsInChildren <Button>(true)) { b.onClick.RemoveAllListeners(); } }); } BoardButtons.transform.Find("BoardButton (" + casilla + ")").GetComponent <Button>().interactable = true; BoardButtons.transform.Find("BoardButton (" + casilla + ")").GetComponent <Image>().sprite = Resources.Load <Sprite>("Dice/dado_" + diceNumber); } } else { //TODO GESITONAR EL ERROR string info = (string)jugadas.Property("info").Value; } DiceGO.SetActive(false); yield return(null); }
//Genera la pregunta de la casilla private void newQuestion(bool quesito, string category, string question, string correct, List <string> incorrects, int position) { //Lo mezcla, genera la posicion e inserta la respuesta correcta ahí Shuffle(ref incorrects); int idCorrect = UnityEngine.Random.Range(0, incorrects.Count + 1); incorrects.Insert(idCorrect, correct); QuestionDataScript.setQuestion(question, incorrects, idCorrect, quesito, category, position, () => StartCoroutine(turno((UserDataScript.getInfo("username"))))); SceneManager.LoadScene("Question Scene", LoadSceneMode.Additive); }