using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System; [Serializable] public class ScoreboardEntriesTable { public List listeScore; public ScoreboardEntriesTable() { listeScore = new List(); } } public class Scoreboard : MonoBehaviour { private string apiUrl = "https://awesomerunner.lagaudiere.uk/score"; public List entries = new List(); public event Action OnEntryAdded; [SerializeField] private ScoreboardView scoreboardView; private void Start() { StartCoroutine(GetScoreboard()); } private IEnumerator GetScoreboard() { Debug.Log("Fetching scoreboard..."); using (UnityWebRequest request = UnityWebRequest.Get(apiUrl)) { yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { string json = request.downloadHandler.text; Debug.Log("Received JSON: " + json); // Désérialiser directement en un tableau ScoreboardEntry[] scoreboardEntriesArray = JsonHelper.FromJson(json); if (scoreboardEntriesArray != null) { entries = new List(scoreboardEntriesArray); SortScoreboardEntriesByHighscore(entries); UpdateScoreboardView(); } } else { Debug.LogError("Erreur lors de la récupération du scoreboard : " + request.error); } } } public void AddScoreboardEntry(ScoreboardEntry entry) { entries.Add(entry); SortScoreboardEntriesByHighscore(entries); UpdateScoreboardView(); StartCoroutine(PostScoreboardEntry(entry)); } private IEnumerator PostScoreboardEntry(ScoreboardEntry entry) { string json = JsonUtility.ToJson(entry); using (UnityWebRequest request = new UnityWebRequest(apiUrl, "POST")) { byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { Debug.Log("Score ajouté avec succès !"); OnEntryAdded?.Invoke(entry); } else { Debug.LogError("Erreur lors de l'ajout du score : " + request.error); } } } private void SortScoreboardEntriesByHighscore(List entries) { entries.Sort((x, y) => y.score.CompareTo(x.score)); } private void UpdateScoreboardView() { Debug.Log("Updating scoreboard view..."); List scoreboardCardDatas = new List(); foreach (var entry in entries) { OnEntryAdded?.Invoke(entry); scoreboardCardDatas.Add(new PlayerScoreboardCardData(entry.pseudo, entry.score.ToString())); } scoreboardView.AddPlayerCards(scoreboardCardDatas); } } public static class JsonHelper { public static T[] FromJson(string json) { string wrappedJson = "{\"items\":" + json + "}"; Wrapper wrapper = JsonUtility.FromJson>(wrappedJson); return wrapper.items; } [System.Serializable] private class Wrapper { public T[] items; } } [Serializable] public class ScoreboardEntriesWrapper { public ScoreboardEntry[] listeScore; }