121 lines
No EOL
3.5 KiB
C#
121 lines
No EOL
3.5 KiB
C#
using System;
|
|
using System.Collections;
|
|
using DungeonSelection;
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
using UnityEngine.Serialization;
|
|
|
|
namespace Scores
|
|
{
|
|
[Serializable]
|
|
public class ScoreEntry
|
|
{
|
|
public int level_id;
|
|
public string player;
|
|
public int score;
|
|
public string timestamp;
|
|
}
|
|
|
|
public class ScoreManager : MonoBehaviour
|
|
{
|
|
public event Action<ScoreEntry[]> ScoresRecieved;
|
|
|
|
private string _getScoresUrl = "https://games.maxdodd.net/get_scores.php";
|
|
private string _postScoreUrl = "https://games.maxdodd.net/set_score.php";
|
|
|
|
private void OnEnable()
|
|
{
|
|
UIEvents.GetScores += GetScores;
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
UIEvents.GetScores -= GetScores;
|
|
}
|
|
|
|
public void GetScores()
|
|
{
|
|
StartCoroutine(GetScoresFromServer());
|
|
}
|
|
|
|
public void PostScore(string planterName, int levelId, int score)
|
|
{
|
|
StartCoroutine(PostScoreToServer(planterName, levelId, score));
|
|
}
|
|
|
|
IEnumerator GetScoresFromServer()
|
|
{
|
|
using (UnityWebRequest request = UnityWebRequest.Get(_getScoresUrl))
|
|
{
|
|
yield return request.SendWebRequest();
|
|
|
|
if (request.result == UnityWebRequest.Result.Success)
|
|
{
|
|
string jsonResponse = request.downloadHandler.text;
|
|
|
|
try
|
|
{
|
|
// Parse the JSON response
|
|
ScoreEntry[] scores = JsonHelper.FromJson<ScoreEntry>(jsonResponse);
|
|
|
|
// Print out the scores
|
|
foreach (ScoreEntry score in scores)
|
|
{
|
|
ScoresRecieved?.Invoke(scores);
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Debug.LogError("Failed to parse scores: " + e.Message);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to fetch scores: " + request.error);
|
|
}
|
|
}
|
|
}
|
|
|
|
IEnumerator PostScoreToServer(string playerName, int levelId, int score)
|
|
{
|
|
string url = _postScoreUrl;
|
|
WWWForm form = new WWWForm();
|
|
form.AddField("player", playerName);
|
|
form.AddField("level_id", levelId);
|
|
form.AddField("score", score);
|
|
|
|
using (UnityWebRequest request = UnityWebRequest.Post(url, form))
|
|
{
|
|
Debug.Log("Sending Request");
|
|
yield return request.SendWebRequest();
|
|
Debug.Log("Request sent");
|
|
|
|
if (request.result == UnityWebRequest.Result.Success)
|
|
{
|
|
Debug.Log("Score submitted: " + request.downloadHandler.text);
|
|
}
|
|
else
|
|
{
|
|
Debug.LogError("Failed to submit score: " + request.error);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Helper class to handle JSON arrays
|
|
public static class JsonHelper
|
|
{
|
|
public static T[] FromJson<T>(string json)
|
|
{
|
|
string wrappedJson = "{\"items\":" + json + "}";
|
|
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(wrappedJson);
|
|
return wrapper.items;
|
|
}
|
|
|
|
[Serializable]
|
|
private class Wrapper<T>
|
|
{
|
|
public T[] items;
|
|
}
|
|
}
|
|
} |