Files
spacerace/Assets/Src/Laps.cs
T
2023-08-01 16:32:49 +10:00

104 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEngine;
public enum SectorColour {
Green,
Purple,
White,
Yellow,
}
[Serializable]
public struct SectorTime {
public int Sector;
public double Seconds;
public override string ToString() => $"{Seconds:0.000}";
}
[Serializable]
public struct Lap {
public string Map;
public int Number;
public List<SectorTime> Sectors;
// 0:1:39
public override string ToString() {
return $"{TimeSpan.FromSeconds(TotalTime()):m\\:ss\\.fff}";
}
public double TotalTime() {
return Sectors.Sum(s => s.Seconds);
}
}
[Serializable]
public class LapJSON {
public string Map;
public List<Lap> Laps = new();
}
// We can't save a dictionary with the Unity JSONUtility
// so we use this to hold a list of maps
public class LapStorage {
public List<LapJSON> Laps = new();
}
static class LapStorageService {
static Dictionary<string, LapJSON> lapsByMap = new();
static string lapStoragePath = Path.Combine(Application.persistentDataPath, "lapStorage.json");
static LapStorageService() {
LapStorage lapStorage = new LapStorage();
try {
string json = File.ReadAllText(lapStoragePath);
JsonUtility.FromJsonOverwrite(json, lapStorage);
} catch {
Debug.Log("No existing lapStorage.json");
}
lapsByMap = lapStorage.Laps.ToDictionary((lapJson) => lapJson.Map);
}
public static LapJSON GetPlayerLaps(string mapName) {
LapJSON currentLaps;
bool found = lapsByMap.TryGetValue(mapName, out currentLaps);
if (!found)
return new LapJSON { Map = mapName, Laps = new List<Lap>() };
return currentLaps;
}
static void Persist() {
LapStorage lapStorage = new LapStorage { Laps = lapsByMap.Values.ToList() };
File.WriteAllText(lapStoragePath, JsonUtility.ToJson(lapStorage));
}
// laps.count
public static int NumberOfCompletions() { return 0; }
// finds your PB in all completions
public static int Rank() { return 1; }
public static void PersistLap(Lap lap) {
LapJSON lapJson;
bool found = lapsByMap.TryGetValue(lap.Map, out lapJson);
if (!found)
lapJson = new LapJSON { Map = lap.Map, Laps = new List<Lap>() };
// Add lap and persist
lapJson.Laps.Add(lap);
lapsByMap[lap.Map] = lapJson;
Persist();
}
public static Lap PB(string mapName) {
return lapsByMap[mapName].Laps
.MinBy(l => l.TotalTime());
}
}