Refactoring game logic
This commit is contained in:
@@ -12,15 +12,14 @@ 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!;
|
||||
private JsonSerializerOptions _jsonOptions;
|
||||
private string _defaultSaveLocation;
|
||||
public const string DEFAULT_SAVE_FILE_NAME = "game.json";
|
||||
|
||||
public SaveFileManager(IFileSystem fileSystem)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
SaveFilePath = _fileSystem.Path.Join(OS.GetUserDataDir(), SAVE_FILE_NAME);
|
||||
_defaultSaveLocation = _fileSystem.Path.Join(OS.GetUserDataDir(), DEFAULT_SAVE_FILE_NAME);
|
||||
|
||||
var resolver = new SerializableTypeResolver();
|
||||
GodotSerialization.Setup();
|
||||
@@ -28,7 +27,7 @@ public class SaveFileManager<T> : ISaveFileManager<T>
|
||||
|
||||
var upgradeDependencies = new Blackboard();
|
||||
|
||||
JsonOptions = new JsonSerializerOptions
|
||||
_jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
Converters = {
|
||||
new SerializableTypeConverter(upgradeDependencies)
|
||||
@@ -39,18 +38,36 @@ public class SaveFileManager<T> : ISaveFileManager<T>
|
||||
}
|
||||
|
||||
|
||||
public async Task<T> ReadFromFile()
|
||||
public Task<T?> ReadFromFile()
|
||||
{
|
||||
if (!_fileSystem.File.Exists(SaveFilePath))
|
||||
if (!_fileSystem.File.Exists(_defaultSaveLocation))
|
||||
throw new FileNotFoundException();
|
||||
return ReadFromFile(_defaultSaveLocation);
|
||||
}
|
||||
|
||||
public async Task<T?> ReadFromFile(string filePath)
|
||||
{
|
||||
if (!_fileSystem.File.Exists(filePath))
|
||||
throw new FileNotFoundException();
|
||||
|
||||
var json = await _fileSystem.File.ReadAllTextAsync(SaveFilePath);
|
||||
return JsonSerializer.Deserialize<T>(json, JsonOptions);
|
||||
var json = await _fileSystem.File.ReadAllTextAsync(filePath);
|
||||
|
||||
return JsonSerializer.Deserialize<T?>(json, _jsonOptions);
|
||||
}
|
||||
|
||||
public async Task WriteToFile(T gameData)
|
||||
public Task WriteToFile(T gameData)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(gameData, JsonOptions);
|
||||
await _fileSystem.File.WriteAllTextAsync(SaveFilePath, json);
|
||||
return WriteToFile(gameData, _defaultSaveLocation, _jsonOptions);
|
||||
}
|
||||
|
||||
public Task WriteToFile(T gameData, string filePath)
|
||||
{
|
||||
return WriteToFile(gameData, filePath, _jsonOptions);
|
||||
}
|
||||
|
||||
public async Task WriteToFile(T gameData, string filePath, JsonSerializerOptions jsonOptions)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(gameData, jsonOptions);
|
||||
await _fileSystem.File.WriteAllTextAsync(filePath, json);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user