Move save logic out of Game
This commit is contained in:
56
Zennysoft.Game.Ma.Implementation/Save/SaveFileManager.cs
Normal file
56
Zennysoft.Game.Ma.Implementation/Save/SaveFileManager.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using Chickensoft.Collections;
|
||||
using Chickensoft.Serialization.Godot;
|
||||
using Chickensoft.Serialization;
|
||||
using Godot;
|
||||
using System.IO.Abstractions;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using Zennysoft.Game.Abstractions;
|
||||
|
||||
namespace Zennysoft.Game.Ma.Implementation;
|
||||
|
||||
public class SaveFileManager<T> : ISaveFileManager<T>
|
||||
{
|
||||
private readonly IFileSystem _fileSystem;
|
||||
public const string SAVE_FILE_NAME = "game.json";
|
||||
public JsonSerializerOptions JsonOptions { get; set; } = default!;
|
||||
|
||||
public string SaveFilePath { get; set; } = default!;
|
||||
|
||||
public SaveFileManager(IFileSystem fileSystem)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
SaveFilePath = _fileSystem.Path.Join(OS.GetUserDataDir(), SAVE_FILE_NAME);
|
||||
|
||||
var resolver = new SerializableTypeResolver();
|
||||
GodotSerialization.Setup();
|
||||
Serializer.AddConverter(new Texture2DConverter());
|
||||
|
||||
var upgradeDependencies = new Blackboard();
|
||||
|
||||
JsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
Converters = {
|
||||
new SerializableTypeConverter(upgradeDependencies)
|
||||
},
|
||||
TypeInfoResolver = JsonTypeInfoResolver.Combine(resolver, WeaponTagEnumContext.Default, ItemTagEnumContext.Default, ElementTypeEnumContext.Default, AccessoryTagEnumContext.Default, ThrowableItemTagEnumContext.Default, UsableItemTagEnumContext.Default, BoxItemTagEnumContext.Default),
|
||||
WriteIndented = true
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public async Task<T> ReadFromFile()
|
||||
{
|
||||
if (!_fileSystem.File.Exists(SaveFilePath))
|
||||
throw new FileNotFoundException();
|
||||
|
||||
var json = await _fileSystem.File.ReadAllTextAsync(SaveFilePath);
|
||||
return JsonSerializer.Deserialize<T>(json, JsonOptions);
|
||||
}
|
||||
|
||||
public async Task WriteToFile(T gameData)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(gameData, JsonOptions);
|
||||
await _fileSystem.File.WriteAllTextAsync(SaveFilePath, json);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user