101 lines
2.6 KiB
C#
101 lines
2.6 KiB
C#
using Godot;
|
|
|
|
using Newlon.Resources;
|
|
using System.Text.Json;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Newlon;
|
|
|
|
public partial class SaveSerializer : Node
|
|
{
|
|
const string SAVE_PATH = "user://save.json";
|
|
public override void _Ready()
|
|
{
|
|
GetTree().AutoAcceptQuit = false;
|
|
LoadGame();
|
|
}
|
|
|
|
public override void _Notification(int what)
|
|
{
|
|
if (what == NotificationWMCloseRequest)
|
|
{
|
|
SaveGame();
|
|
GetTree().Quit();
|
|
}
|
|
}
|
|
public static void SaveGame()
|
|
{
|
|
var access = FileAccess.Open(SAVE_PATH, FileAccess.ModeFlags.Write);
|
|
var playerProgress = PlayerProgress.Instance;
|
|
var save = new SaveData
|
|
{
|
|
|
|
SFXVolume = (float)Settings.SFX,
|
|
MusicVolume = (float)Settings.Music,
|
|
SplashSeen = Settings.Splash,
|
|
Money = playerProgress.Money,
|
|
SeedpacketSlots = playerProgress.MaxSeedpackets,
|
|
PlayerPlants = [],
|
|
|
|
SaveGameVersion = (string)ProjectSettings.GetSetting("application/config/version")
|
|
};
|
|
|
|
foreach (var plant in playerProgress.PlayerPlants)
|
|
{
|
|
save.PlayerPlants.Add(plant.GetInternalID());
|
|
}
|
|
|
|
access.StoreString(JsonSerializer.Serialize<SaveData>(save));
|
|
|
|
access.Close();
|
|
}
|
|
public static void LoadGame()
|
|
{
|
|
if (FileAccess.FileExists(SAVE_PATH) == false)
|
|
{
|
|
InitiateCleanSave();
|
|
return;
|
|
}
|
|
|
|
var access = FileAccess.Open(SAVE_PATH, FileAccess.ModeFlags.Read);
|
|
|
|
var parsed = JsonSerializer.Deserialize<SaveData>(access.GetAsText());
|
|
|
|
Settings.SFX = parsed.SFXVolume;
|
|
Settings.Music = parsed.MusicVolume;
|
|
Settings.Splash = parsed.SplashSeen;
|
|
|
|
AudioServer.SetBusVolumeDb(2, Mathf.LinearToDb(Mathf.Exp((float)Settings.SFX) - 1));
|
|
AudioServer.SetBusVolumeDb(1, Mathf.LinearToDb(Mathf.Exp((float)Settings.Music) - 1));
|
|
|
|
var playerProgress = PlayerProgress.Instance;
|
|
playerProgress.MaxSeedpackets = parsed.SeedpacketSlots;
|
|
playerProgress.PlayerPlants = [];
|
|
|
|
foreach (var plantId in parsed.PlayerPlants)
|
|
{
|
|
playerProgress.PlayerPlants.Add((PlantResource)GameRegistry.GetEntityByName(plantId));
|
|
}
|
|
|
|
|
|
access.Close();
|
|
}
|
|
private static void InitiateCleanSave()
|
|
{
|
|
PlayerProgress.Instance.PlayerPlants = new List<PlantResource>([(PlantResource)GameRegistry.GetEntityByName("peashooter")]);
|
|
PlayerProgress.Instance.Money = 0;
|
|
|
|
SaveGame();
|
|
}
|
|
private partial class SaveData
|
|
{
|
|
public float SFXVolume { get; set; }
|
|
public float MusicVolume { get; set; }
|
|
public string SaveGameVersion { get; set; }
|
|
public bool SplashSeen { get; set; }
|
|
public List<string> PlayerPlants { get; set; }
|
|
public int Money { get; set; } = 0;
|
|
public int SeedpacketSlots { get; set; } = 6;
|
|
public List<string> FinishedLevels { get; set; } = new();
|
|
}
|
|
}
|