Pong/Scripts/Managers/SettingsManager.cs
Fries 425bf2ad27 make a settings menu and general refactoring
i added more to the main menu, as it has a settings menu now, that stores its files with json. i also changed the font to atkinson hyperlegible and made a BaseMenu class that takes care of the screen scaling for menus.

i also refactored the project folder structure to make it more organized.
2023-05-20 21:42:38 -07:00

78 lines
1.9 KiB
C#

using System;
using System.Text.Json;
using System.Threading.Tasks;
using Godot;
using Pong.Scripts.Data;
namespace Pong.Scripts.Managers;
public partial class SettingsManager : Node
{
private const string SettingsPath = "user://settings.json";
public Settings SettingsData = Settings.Default;
private static readonly JsonSerializerOptions SerializerOptions = new() { IncludeFields = true };
public event Action SettingsChanged;
public override async void _EnterTree()
{
await LoadSettings();
}
/// <summary>
/// load the settings data from the filesystem.
/// </summary>
private async Task LoadSettings()
{
try
{
if (!FileAccess.FileExists(SettingsPath))
{
await SaveSettings(Settings.Default);
return;
}
using var file = await OpenSettingsFile(FileAccess.ModeFlags.Read);
SettingsData =
await Task.Run(() => JsonSerializer.Deserialize<Settings>(file.GetAsText(), SerializerOptions));
SettingsChanged?.Invoke();
}
catch (Exception e)
{
PrintFileError(e);
}
}
/// <summary>
/// open the settings file from the filesystem.
/// </summary>
/// <returns> a godot FileAccess object.</returns>
private static async Task<FileAccess> OpenSettingsFile(FileAccess.ModeFlags flag)
{
return await Task.Run(() => FileAccess.Open(SettingsPath, flag));
}
internal async Task<bool> SaveSettings(Settings settings)
{
try
{
using var file = await OpenSettingsFile(FileAccess.ModeFlags.WriteRead);
var json = await Task.Run(() => JsonSerializer.Serialize(settings, SerializerOptions));
await Task.Run(() => file.StoreBuffer(json.ToUtf8Buffer()));
SettingsData = settings;
SettingsChanged?.Invoke();
return true;
}
catch (Exception e)
{
PrintFileError(e);
return false;
}
}
private static void PrintFileError(Exception e)
{
GD.PrintErr($"a {e.GetType()} has occured while trying to load the settings file: {e}.");
GD.PrintErr("default settings will be used.");
}
}