LapService

This commit is contained in:
ntr committed 2023-08-29 21:05:43 +10:00
1 parent c66c6654c5
commit cebc2ef588
8 files changed
+63 -125

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
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 LapService {
static string playerDataPath = Path.Combine(Application.persistentDataPath, "playerData.json");
string _mapName;
PlayerData _player;
PbDTO _pb;
public Lap PB;
public LapService(string mapName) {
_mapName = mapName;
LoadPlayerData();
}
public IEnumerator GetPb() {
string uri = $"localhost:40080/Pb?userId={_player.Id}&mapName={_mapName}";
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);
SetPb(req.downloadHandler.text);
break;
}
}
}
PbDTO SetPb(string json) {
PbDTO dto = JsonConvert.DeserializeObject<PbDTO>(json);
_pb = dto;
PB = new Lap {
Map = _pb.Map,
Sectors = dto.Sectors.Select((d, i) => new SectorTime { Sector = i + 1, Seconds = d }).ToList(),
};
return dto;
}
public IEnumerator PostLap(Lap lap) {
LapDTO dto = new LapDTO {
Id = Guid.NewGuid(),
UserId = _player.Id,
Map = _mapName,
Time = lap.TotalTime,
Sectors = lap.Sectors.Select(s => s.Seconds).ToList(),
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 {dto}");
}
}
void LoadPlayerData() {
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();
}
}
PlayerData CreatePlayerData() {
_player = new PlayerData { Id = Guid.NewGuid() };
Debug.Log(JsonConvert.SerializeObject(_player));
File.WriteAllText(playerDataPath, JsonConvert.SerializeObject(_player));
return _player;
}
}