You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.6 KiB
97 lines
2.6 KiB
using System;
|
|
using Godot;
|
|
using Godot.Collections;
|
|
using FileAccess = Godot.FileAccess;
|
|
|
|
namespace Babushka.scripts.CSharp.Common.Savegame;
|
|
|
|
/// <summary>
|
|
/// Handles the saving and loading of game states.
|
|
/// Holds the central SaveData object that serves as a temporary SaveFile.
|
|
/// Automatically writes to disk on every scene change.
|
|
/// </summary>
|
|
public static class SavegameService
|
|
{
|
|
public static readonly string SavePath = "user://babushka_savegame.json";
|
|
|
|
public static Dictionary<string, string> SaveDatas = new ();
|
|
|
|
public static bool _loaded = false;
|
|
|
|
|
|
/// <summary>
|
|
/// Adds or overwrites an entry in the SaveData dictionary.
|
|
/// </summary>
|
|
/// <param name="saveData"></param>
|
|
public static void AppendSave(SaveData saveData)
|
|
{
|
|
string key = string.Concat(saveData.SceneName, "_", saveData.Id);
|
|
|
|
if (SaveDatas.TryGetValue(key, out var value))
|
|
{
|
|
SaveDatas[key] = saveData.JsonPayload;
|
|
}
|
|
else
|
|
{
|
|
SaveDatas.Add(key, saveData.JsonPayload);
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Checks the SaveData dictionary for an entry and returns the jsondata as a string for it.
|
|
/// Requires the scenename and object ID for lookup.
|
|
/// </summary>
|
|
/// <param name="sceneName"></param>
|
|
/// <param name="id"></param>
|
|
/// <returns></returns>
|
|
public static string GetSaveData(string sceneName, string id)
|
|
{
|
|
string saveData = "";
|
|
|
|
string key = string.Concat(sceneName, "_", id);
|
|
|
|
if (!_loaded)
|
|
{
|
|
GD.Print("SavegameService: SaveFile not loaded.");
|
|
return saveData;
|
|
}
|
|
|
|
if (SaveDatas.ContainsKey(key))
|
|
{
|
|
saveData = SaveDatas[key];
|
|
}
|
|
|
|
return saveData;
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Writes the contents of the current SaveData dictionary to disk as a json file.
|
|
/// </summary>
|
|
public static void Save()
|
|
{
|
|
string json = Json.Stringify(SaveDatas, indent: "\t");
|
|
using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Write);
|
|
file.StoreString(json);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads the current savegame file from disk and parses it into the SaveData dictionary.
|
|
/// </summary>
|
|
public static void Load()
|
|
{
|
|
try
|
|
{
|
|
string saveDataJson = FileAccess.GetFileAsString(SavePath);
|
|
SaveDatas = Json.ParseString(saveDataJson).AsGodotDictionary<string, string>();
|
|
}
|
|
catch(Exception e)
|
|
{
|
|
GD.PrintRich(e.Message);
|
|
return;
|
|
}
|
|
|
|
_loaded = true;
|
|
}
|
|
} |