92 lines
2.7 KiB
C#
92 lines
2.7 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.IO;
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
using UnityEngine;
|
|
using UnityEngine.Networking;
|
|
using UnityEngine.UIElements;
|
|
|
|
using SpaceRace.Shared;
|
|
|
|
public class PlayerData {
|
|
public Guid Id;
|
|
}
|
|
|
|
public class LapFetchService {
|
|
static string playerDataPath = Path.Combine(Application.persistentDataPath, "playerData.json");
|
|
string _mapName;
|
|
PlayerData player;
|
|
|
|
public LapFetchService(string mapName) {
|
|
_mapName = mapName;
|
|
try {
|
|
string json = File.ReadAllText(playerDataPath);
|
|
player = JsonConvert.DeserializeObject<PlayerData>(json);
|
|
Debug.Log($"Loaded player data {player}");
|
|
} catch {
|
|
Debug.Log("No existing playerData.json");
|
|
CreatePlayerData();
|
|
}
|
|
}
|
|
|
|
public IEnumerator GetPb() {
|
|
string uri = $"localhost:40080/Pb?userId={player.Id}&mapName={_mapName}";
|
|
Debug.Log(uri);
|
|
using (UnityWebRequest req = UnityWebRequest.Get(uri)) {
|
|
yield return req.SendWebRequest();
|
|
|
|
switch (req.result) {
|
|
case UnityWebRequest.Result.ConnectionError:
|
|
case UnityWebRequest.Result.DataProcessingError:
|
|
Debug.LogError("Error: " + req.error);
|
|
break;
|
|
case UnityWebRequest.Result.ProtocolError:
|
|
Debug.LogError("HTTP Error: " + req.error);
|
|
break;
|
|
case UnityWebRequest.Result.Success:
|
|
Debug.Log("Received: " + req.downloadHandler.text);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
public IEnumerator PostLap(Lap lap) {
|
|
LapDTO dto = new LapDTO {
|
|
Id = Guid.NewGuid(),
|
|
UserId = player.Id,
|
|
Map = _mapName,
|
|
Time = lap.TotalTime,
|
|
Created = DateTimeOffset.UtcNow,
|
|
};
|
|
|
|
Debug.Log(JsonConvert.SerializeObject(dto));
|
|
|
|
using (UnityWebRequest req = UnityWebRequest.Post("localhost:40080/Lap", JsonConvert.SerializeObject(dto), "application/json")) {
|
|
yield return req.SendWebRequest();
|
|
|
|
if (req.result != UnityWebRequest.Result.Success) {
|
|
Debug.Log(req.error);
|
|
}
|
|
|
|
Debug.Log("posted lap");
|
|
}
|
|
}
|
|
|
|
// laps.count
|
|
public int NumberOfCompletions() { return 0; }
|
|
|
|
// finds your PB in all completions
|
|
public int Position() { return 1; }
|
|
|
|
PlayerData CreatePlayerData() {
|
|
player = new PlayerData { Id = Guid.NewGuid() };
|
|
Debug.Log(JsonConvert.SerializeObject(player));
|
|
File.WriteAllText(playerDataPath, JsonConvert.SerializeObject(player));
|
|
return player;
|
|
}
|
|
}
|