SCRIPTS DONT LOSE FUCK
unknown
csharp
2 years ago
26 kB
3
Indexable
Start of Battle Screen using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// Specifically for the battle /// </summary> public class BattleScreen : MonoBehaviour { public BattleScreen battleScreen; /* You will need to do a few things in this script: * 1. When the match starts and is not continued, be sure the player only chooses defense not offense. When a player continues it should shows offense then when returned from the server defense * 2. Cancel/back returns the player to main menu * 3. When entering the screen make sure the player's health is adjusted accordingly * 4. Allow the user to choose what section to attack and defend * 5. Animate Attack * 6. Make sure after an attack the health is adjusted * 7. You should have a game information variable in here and a function for it to be set from continue or start screens */ public void OnClick() { GoNextScreen(battleScreen.gameObject); } public void GoNextScreen(GameObject nextScreen) { this.GetComponent<ScreenChangeScript>().SetNextScreen(nextScreen); this.GetComponent<ScreenChangeScript>().SetInteractivity(false); this.GetComponent<ScreenChangeScript>().SetFade(true); } } End of battlescreen ----------------------------------------------------------------------------------- Start of continuescreen using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; /// <summary> /// Class for use in continuing battles that have been already made /// </summary> public class ContinueScreen : MonoBehaviour { /* You will need to do a few things in this script: * 1. When the screen is loading, look for other player data on the server (this can be a function called from another screen or button) * 2. When the user clicks one of the prefabs the right user information will be sent to the server and pass that information to the battle screen * 3. Return to main screen when cancel is clicked * 4. Screen is created with a scroll rect and the prefabs populate it * 5. When getting the user data if you put it inside another array you will have to add information before and after it ("{\"users\":[" + data + "]}" */ /// <summary> Prefab for holding user data </summary> [SerializeField] GameObject userPrefab; [SerializeField] private MainMenuScreen mainMenu; [SerializeField] GameObject scrollContent; private UserList opponents; private TextMeshProUGUI buttonTxt; private bool buttonsSpawnedYet; public TextMeshProUGUI statusTxt; public string buttonText; public BattleScreen battleScreen; private GameList gameList; private GameData gameData; /// <summary> /// Used to spawn the objects into the scroll rect /// </summary> ///this is testing code (In class with rich) public void GetOtherUsers() { WebRequestClass.Instance.returnFunction += ReturnSuccess; // Then sets up the coroutine to get the data WebRequestClass.Instance.SendWebRequest(Constants.LIST_BATTLES_URL + "?userid=" + WebRequestClass.Instance.userInformation.UserID); } private void ReturnSuccess(string results) { Debug.Log(results); results = "{" + "\"" + "currentGames" + "\"" + ":" + results + "}"; //Deserialize the JSON //Temporary shit gameList = JsonUtility.FromJson<GameList>(results); WebRequestClass.Instance.returnFunction -= ReturnSuccess; if (buttonsSpawnedYet == false) { SpawnObjects(); } } public void OnClick() { GoNextScreen(mainMenu.gameObject); //DestroyButtons(); } public void GoNextScreen(GameObject nextScreen) { this.GetComponent<ScreenChangeScript>().SetNextScreen(nextScreen); this.GetComponent<ScreenChangeScript>().SetInteractivity(false); this.GetComponent<ScreenChangeScript>().SetFade(true); DestroyButtons(); } private void DestroyButtons() { //GameObject[] buttonsDestroy = GameObject.FindGameObjectsWithTag("ButtonToDelete"); //foreach(GameObject button in buttonsDestroy) { Destroy(button); buttonsSpawnedYet = false; } foreach (Button btnDeletePlx in scrollContent.GetComponentsInChildren<Button>()) { Destroy(btnDeletePlx.gameObject); } buttonsSpawnedYet = false; } private void SpawnObjects() { Vector3 pos = Vector3.zero; for (int i = 0; i < gameList.currentGames.Count; i++) { GameObject newPrefab = Instantiate(userPrefab, scrollContent.transform); buttonTxt = newPrefab.GetComponentInChildren<TextMeshProUGUI>(); buttonTxt.text = "ID: " + gameList.currentGames[i].GameID; if (i == 0) { pos = newPrefab.transform.position; } newPrefab.transform.position = new Vector3(newPrefab.transform.position.x, pos.y, newPrefab.transform.position.z); pos.y -= 1.5f; int rememberedGameID = gameList.currentGames[i].GameID; newPrefab.GetComponent<Button>().onClick.AddListener(() => { WebRequestClass.Instance.returnFunction += ResumeBattleTime; WebRequestClass.Instance.SendWebRequest(Constants.GET_BATTLE_INFO_URL + "?gameid=" + rememberedGameID); }); } buttonsSpawnedYet = true; //for () //{ // TODO: You will need to create a variable to hold the user data out here then use it inside this anonymous function // This is an anonymous method call. Easiest for not create a class for each prefab and having an event call back here while it holds data //newListItem.GetComponent<Button>().onClick.AddListener(() => //{ // TODO: Add subscription and call the web request //}); //} } private void ResumeBattleTime(string data) { WebRequestClass.Instance.returnFunction -= ResumeBattleTime; string storage = data; GoNextScreen(battleScreen.gameObject); //DestroyButtons(); } } End of continuescreen ------------------------------------------------------------------------------ Start of CreateUserScreen using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// This screen will allow a user to create a user /// IMPORTANT: The Compile errors are intended here. We will work through them in class to fix, and they give you hints of what you should create. /// </summary> public class CreateUserScreen : MonoBehaviour { /// <summary> Inputfield for inputting user information, used to edit the info through the buttons </summary> [SerializeField] private InputField inputField; /// <summary> Access to the main screen to make transition easier </summary> [SerializeField] private MainMenuScreen mainMenuScreen; /// <summary> /// Button function for adding a character to the input screen /// </summary> /// <param name="character">Character to be added</param> public void SetChar(string character) { inputField.text += character; } /// <summary> /// This will be the function the WebRequestClass calls once the network code has been completed /// </summary> /// <param name="data">JSON data on the return</param> public void ReturnSuccess(string data) { data = data.Substring(1, data.Length - 2); // TODO: You may need to change this is you didn't name you user variable or class the same as mine WebRequestClass.Instance.userInformation = JsonUtility.FromJson<UserInformation>(data); // This is specifically how you unsubsribe to an event. WebRequestClass.Instance.returnFunction -= ReturnSuccess; // Set's player prefs and uses the constants class for making sure we never copy and past incorrectly PlayerPrefs.SetString(Constants.prefPlayerEmail, inputField.text); // Resets input field ExitClicked(); //Goes to main menu and calls a function to get the userid (We should already have it but just in case) //TODO: This function may not be named the same on yours mainMenuScreen.CheckForEmail(); NextScreen(mainMenuScreen.gameObject); } /// <summary> /// When the enter button is clicked create the player /// </summary> public void EnterClicked() { // Subscribes to the event first WebRequestClass.Instance.returnFunction += ReturnSuccess; // Then sets up the coroutine to get the data WebRequestClass.Instance.SendWebRequest(Constants.CREATE_PLAYER_URL + "?email=" + inputField.text); } /// <summary> /// Deletion button for input field /// </summary> public void DelClicked() { // Error checking if (inputField.text.Length > 0) { inputField.text = inputField.text.Substring(0, inputField.text.Length - 1); } } /// <summary> /// Sets input field to blank when leaving /// </summary> public void ExitClicked() { inputField.text = ""; // TODO: This function in the main menu checks for the user last logged in. It disables the start and continue buttons (since the user must log in each time) // if that exists, populate the login field and enable the loging button. // if not, disable the login button. mainMenuScreen.CheckForEmail(); } /// <summary> /// Hooks up to the nice Screen Change Script which will do your fade for you. Works better as a state machine but this is easier to understand /// </summary> /// <param name="nextScreen">GameObject with ScreenChangeScript on it to go to the next screen</param> public void NextScreen(GameObject nextScreen) { this.GetComponent<ScreenChangeScript>().SetNextScreen(nextScreen); this.GetComponent<ScreenChangeScript>().SetInteractivity(false); this.GetComponent<ScreenChangeScript>().SetFade(true); } } End of CreateUserScreen ----------------------------------------------------------------------------------------------------- Start of MainMenuScreen using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; /// <summary> /// This class is meant for use in the Main Menu, for logging in and making sure the user can start a game. /// </summary> public class MainMenuScreen : MonoBehaviour { private string lastVictim; [SerializeField] public Button LoginBtn; [SerializeField] public Button StartBtn; [SerializeField] public Button ContinueBtn; [SerializeField] public Button CreateBtn; [SerializeField] private TMP_InputField userInput; [SerializeField] private TextMeshProUGUI displayMessage; [SerializeField] private CreateUserScreen createUserScreen; [SerializeField] private StartBattleScreen startBattleScreen; [SerializeField] private ContinueScreen continueScreen; private void Start() { CheckForEmail(); } public void CheckForEmail() { //Fill in the text field using userInformation //WebRequestClass.Instance.userInformation.email StartBtn.interactable = false; ContinueBtn.interactable = false; LoginBtn.interactable = false; if (WebRequestClass.Instance.userInformation.email != null && WebRequestClass.Instance.userInformation.email != "") { lastVictim = WebRequestClass.Instance.userInformation.email; userInput.text = lastVictim; displayMessage.text = "Welcome back, " + lastVictim + ". Go outside or something. Or just login."; EnableLogin(); } else { lastVictim = ""; } } public void EnableLogin() { if (userInput.text != null && userInput.text != "") { LoginBtn.interactable = true; } else { LoginBtn.interactable = false; } } public void AttemptLogin() { WebRequestClass.Instance.returnFunction += HeckYeahLoggedIn; WebRequestClass.Instance.SendWebRequest(Constants.GET_URL + "?email=" + userInput.text); } public void HeckYeahLoggedIn(string data) { data = data.Substring(1, data.Length - 2); WebRequestClass.Instance.userInformation = JsonUtility.FromJson<UserInformation>(data); //This is to remove from evenet WebRequestClass.Instance.returnFunction -= HeckYeahLoggedIn; if (data != "") { StartBtn.interactable = true; ContinueBtn.interactable = true; displayMessage.text = userInput.text + "(ID: " + WebRequestClass.Instance.userInformation.UserID + ") successfully logged in."; } else { StartBtn.interactable = false; ContinueBtn.interactable = false; displayMessage.text = "Login error: User " + userInput.text + "not found"; } } public void CreateUserScreen() { GoNextScreen(createUserScreen.gameObject); } public void StartBattleScreen() { GoNextScreen(startBattleScreen.gameObject); startBattleScreen.GetOtherUsers(); } public void ContinueScreen() { GoNextScreen(continueScreen.gameObject); continueScreen.GetOtherUsers(); } public void GoNextScreen(GameObject nextScreen) { this.GetComponent<ScreenChangeScript>().SetNextScreen(nextScreen); this.GetComponent<ScreenChangeScript>().SetInteractivity(false); this.GetComponent<ScreenChangeScript>().SetFade(true); } private void Update() { if(Input.GetKeyUp(KeyCode.Escape)) { UnityEditor.EditorApplication.isPlaying = true; } } /* You will need to do a few things in this script: * 1. On Start use player prefs or serialize the last user who logged in. * 2. Populate that string in the user name input field (or set the field to empty). Disable the buttons for start and continue * 3. When the user clicks the Login Button make a request to list_currentplayer.php passing the email in the input field. Wait for a response * 4. If you get back a empty string/response - the user was not found. Otherwise you will get back serialized text with the user name and user ID. Enable start and continue if user *was* found. * 5. Add Back button to quit application * 6. Add button traversal for Start and Continue (and only enable those buttons if the user was found) * Functions to create * CheckForEmail: Disable Start/Continue buttons. Check if the saves user name exists. if it does, populate the field and enable login. Else Disable login button. * Add functions for the input field to call when the data changes to enable login * Add code hooked up to the login button to make the list_currentplayer.php request * Add code to parse the response from list_currentplayer.php to save the current user (other screens will need it) and enable to start/continue buttons * */ } End of MainMenuScreen ------------------------------------------------------------------------------------ Start of StartBattleScreen using System.Collections; using System.Collections.Generic; using TMPro; using Unity.VisualScripting; using UnityEngine; using UnityEngine.UI; /// <summary> /// This screen will be used to visualize a list of other players to battle against /// </summary> public class StartBattleScreen : MonoBehaviour { /* You will need to do a few things in this script: * 1. When the screen is loading, look for other player data on the server (this can be a function called from another screen or button) * 2. When the user clicks one of the prefabs the right user information will be sent to the server and pass that information to the battle screen * 3. Return to main screen when cancel is clicked * 4. Screen is created with a scroll rect and the prefabs populate it * 5. When getting the user data if you put it inside another array you will have to add information before and after it ("{\"users\":[" + data + "]}" */ /// <summary> Prefab for holding user data </summary> [SerializeField] GameObject userPrefab; [SerializeField] private MainMenuScreen mainMenu; [SerializeField] GameObject scrollContent; private UserList opponents; private TextMeshProUGUI buttonTxt; private bool buttonsSpawnedYet; public TextMeshProUGUI statusTxt; public BattleScreen battleScreen; /// <summary> /// Used to spawn the objects into the scroll rect /// </summary> ///this is testing code (In class with rich) public void GetOtherUsers() { WebRequestClass.Instance.returnFunction += ReturnSuccess; // Then sets up the coroutine to get the data WebRequestClass.Instance.SendWebRequest(Constants.LIST_OTHER_PLAYERS_URL + "?userid=" + WebRequestClass.Instance.userInformation.UserID); } private void ReturnSuccess(string results) { Debug.Log(results); results = "{" + "\"" + "users" + "\"" + ":" + results + "}"; //Deserialize the JSON WebRequestClass.Instance.returnFunction -= ReturnSuccess; //Temporary shit opponents = JsonUtility.FromJson<UserList>(results); if (!buttonsSpawnedYet) { SpawnObjects(); } } public void OnClick() { GoNextScreen(mainMenu.gameObject); } public void GoNextScreen(GameObject nextScreen) { this.GetComponent<ScreenChangeScript>().SetNextScreen(nextScreen); this.GetComponent<ScreenChangeScript>().SetInteractivity(false); this.GetComponent<ScreenChangeScript>().SetFade(true); DestroyButtons(); } private void DestroyButtons() { //GameObject[] buttonsDestroy = GameObject.FindGameObjectsWithTag("ButtonToDelete"); //foreach(GameObject button in buttonsDestroy) { Destroy(button); buttonsSpawnedYet = false; } foreach (Button btnDeletePlx in scrollContent.GetComponentsInChildren<Button>()) { Destroy(btnDeletePlx.gameObject); } buttonsSpawnedYet = false; } private void SpawnObjects() { Vector3 pos = Vector3.zero; for (int i = 0; i < opponents.users.Count; i++) { GameObject newPrefab = Instantiate(userPrefab, scrollContent.transform); buttonTxt = newPrefab.GetComponentInChildren<TextMeshProUGUI>(); buttonTxt.text = "Player: " + opponents.users[i].email; if (i == 0) { pos = newPrefab.transform.position; } newPrefab.transform.position = new Vector3(newPrefab.transform.position.x, pos.y, newPrefab.transform.position.z); pos.y -= 1.5f; int enemyID = opponents.users[i].UserID; newPrefab.GetComponent<Button>().onClick.AddListener(() => { WebRequestClass.Instance.returnFunction += StartBattleTime; // Then sets up the coroutine to get the data WebRequestClass.Instance.SendWebRequest(Constants.START_BATTLE_URL + "?userid=" + WebRequestClass.Instance.userInformation.UserID + "&opponentid=" + enemyID); }); } buttonsSpawnedYet = true; //for () //{ // TODO: You will need to create a variable to hold the user data out here then use it inside this anonymous function // This is an anonymous method call. Easiest for not create a class for each prefab and having an event call back here while it holds data //newListItem.GetComponent<Button>().onClick.AddListener(() => //{ // TODO: Add subscription and call the web request //}); //} } private void StartBattleTime(string data) { WebRequestClass.Instance.returnFunction -= StartBattleTime; string storage = data; GoNextScreen(battleScreen.gameObject); } } End of StartBattleScreen ------------------------------------------- Start of userInformation using System; using System.Collections; using System.Collections.Generic; //This stores the user information. [Serializable] public class UserInformation { public int UserID; public string email; } [Serializable] public class UserList { public List<UserInformation> users; } [Serializable] public class GameData { public int GameID; public int Player1ID; public int Player1Health; public int Player2Health; public int Player2ID; public int WhosTurn; } [Serializable] public class GameList { public List<GameData> currentGames; } End of UserInformation ------------------------------------------------------------ Start of webRequestClass using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Rendering; /// <summary> /// This class should have a generic coroutine that all classes can use to call the server and return data /// </summary> public class WebRequestClass : MonoBehaviour { /* This class should: * 1. Have a public function that everyone can use to create a UWR coroutine. Pass in a string of the web site to connect to. * 2. Check to see if an action is already running, if so do not start another one (I'd use a IEnumerator variable or a string or bool) * 3. Have an event call back to the returning the UWN response data through a string, the event should be a void (string). * WHY? So any screen can say "Hey connect to this web page and notify me when its complete" * 4. Have information on the user class to be used anywhere for ease of use (user class variable) * 5. The data is not completely filtered when receiving it from the server. You have to remove the array brackets on the data: www.text.Substring(1, www.text.Length - 2) */ /// <summary> This is a static instance of the class, allowing you to use it anywhere! </summary> /// public UserInformation userInformation = new UserInformation(); public static WebRequestClass Instance { get; private set; } private string website; public delegate void ReturnWebFunction(string data); public event ReturnWebFunction returnFunction; private bool requestInProgress; /// <summary> /// Awake is used so this instance is created before any Start functions is used /// </summary> private void Awake() { requestInProgress = false; Instance = this; } public void SendWebRequest(string websiteURL) { if(requestInProgress == false) { website = websiteURL; StartCoroutine(SendWebRequestCR()); } else { Debug.LogWarning("A request is already in progress, ignoring " + websiteURL); } } private IEnumerator SendWebRequestCR() { string results; Debug.Log("About to request: " + website); requestInProgress = true; using (UnityWebRequest uwr = UnityWebRequest.Get(website)) { yield return uwr.SendWebRequest(); //Once we get there, our food is ready. if (string.IsNullOrEmpty(uwr.error)) { results = uwr.downloadHandler.text; } else { Debug.LogWarning("Website: " + website + " gave error: " + uwr.error); results = uwr.error; } Debug.Log("Got results: " + results); requestInProgress=false; returnFunction(results); } } } End of webrequestclass ---------------------------------------------------------------------------------- Start of constants /// <summary> /// Place to hold constant static data that should never change /// </summary> public static class Constants { /// <summary> Player Pref email name </summary>. /// Use this for playherPrefs or serializing a string. public static string prefPlayerEmail = "playerEmail"; /// <summary> Base URL </summary> public static string URL = "http://localhost:8080/"; /// <summary> This is what you call to create the player </summary> public static string CREATE_PLAYER_URL = URL + "create_player.php"; //Get the current player public static string GET_URL = URL + "list_currentplayer.php"; /// <summary> This is what you call to start a battle with a player </summary> public static string START_BATTLE_URL = URL + "create_battle.php"; /// <summary> This is what you call to get a list of battles </summary> public static string LIST_BATTLES_URL = URL + "list_currentBattles.php"; /// <summary> This is what you call to get info on a specific battle </summary> public static string GET_BATTLE_INFO_URL = URL + "list_currentBattle.php"; /// <summary> This is what you call to list players to battle </summary> public static string LIST_OTHER_PLAYERS_URL = URL + "list_otherplayers.php"; //This is for startnewbattle shit /// <summary> This is what you call to send a player's defensive choice </summary> public static string BATTLE_DEFENSE_URL = URL + "battle_defense.php"; /// <summary> This is what you call to send a player's offensive choice </summary> public static string BATTLE_OFFENSE_URL = URL + "battle_attack.php"; }
Editor is loading...
Leave a Comment