using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class DisplayFinalResults : MonoBehaviour { public Text resultsDisplayText; // Assign this in the inspector to a UI Text element where results will be displayed public GameObject errorPanel; // A panel to display in case of errors private string resultsUrl = "https://smarthubs.media.tuwien.ac.at/api/get_all_player_points/" ; //server api to show // display the results, such as at the end of a game. public void FetchAndDisplayResults() { StartCoroutine(GetFinalResults()); } public IEnumerator GetFinalResults() { string gameNumber = FindObjectOfType().GetGameNumber(); // Assuming the server expects a game ID to fetch the results WWWForm form = new WWWForm(); //form.AddField("game_id", gameNumber); resultsUrl="https://smarthubs.media.tuwien.ac.at/api/get_all_player_points/"; resultsUrl= resultsUrl + "" + gameNumber; Debug.Log("display:"+ resultsUrl); using (UnityWebRequest www = UnityWebRequest.Get(resultsUrl)) //use get instead of post, since no modification needed in server side { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log(www.error); if (errorPanel != null) { errorPanel.SetActive(true); // Show error panel if there is an error } } else { Debug.Log("Results fetched successfully"); // Assuming the server returns results in a simple text format //resultsDisplayText.text = www.downloadHandler.text; // Display the results // Parse and display the results string rawResults = www.downloadHandler.text; // Rraw jason text from the server Debug.Log("Raw results: " + rawResults); DisplayResultsNicely(rawResults); } } } private void DisplayResultsNicely(string rawResults) { // Trim curly braces and split the string into key-value pairs //rawResults = rawResults.Trim('{', '}'); rawResults = rawResults.Trim('{', '}').Trim(); string[] playerEntries = rawResults.Split(','); string formattedResults = ""; foreach (string entry in playerEntries) { // Split each key-value pair string[] keyValue = entry.Split(':'); if (keyValue.Length == 2) { string playerNumber = keyValue[0].Trim('"'); // Remove extra quotes string playerPoints = keyValue[1].Trim('}', '"'); // Ensure no extra curly braces formattedResults += "Player " + playerNumber + ": " + playerPoints + " points\n"; Debug.Log("Parsed result for Player " + playerNumber + ": " + playerPoints + " points"); } } // Display the formatted results resultsDisplayText.text = formattedResults; Debug.Log("Final Display: " + formattedResults); } }