- Created README.md with project description and setup instructions - Added project configuration files (TheGame.csproj, TheGame.sln, project.godot) - Implemented main game scenes (MainMenu.tscn, Game.tscn, LoadGameMenu.tscn) - Developed game logic in C# scripts (Game.cs, MainMenu.cs, LoadGameMenu.cs, PauseMenu.cs, SaveManager.cs) - Introduced save/load functionality and timer display - Included icon.svg for game branding
111 lines
3.3 KiB
C#
111 lines
3.3 KiB
C#
using Godot;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
|
|
namespace TheGame
|
|
{
|
|
public class SaveData
|
|
{
|
|
public float GameTime { get; set; }
|
|
public DateTime SaveDate { get; set; }
|
|
public string SaveName { get; set; }
|
|
}
|
|
|
|
public class SaveManager
|
|
{
|
|
private readonly string _saveDirectory;
|
|
|
|
public SaveManager()
|
|
{
|
|
_saveDirectory = Path.Combine(OS.GetExecutablePath().GetBaseDir(), "saves");
|
|
|
|
// Skapa saves mapp om den inte finns
|
|
if (!Directory.Exists(_saveDirectory))
|
|
{
|
|
Directory.CreateDirectory(_saveDirectory);
|
|
}
|
|
}
|
|
|
|
public void SaveGame(float gameTime)
|
|
{
|
|
var saveData = new SaveData
|
|
{
|
|
GameTime = gameTime,
|
|
SaveDate = DateTime.Now,
|
|
SaveName = $"Save_{DateTime.Now:yyyyMMdd_HHmmss}"
|
|
};
|
|
|
|
string fileName = $"{saveData.SaveName}.json";
|
|
string filePath = Path.Combine(_saveDirectory, fileName);
|
|
|
|
try
|
|
{
|
|
string jsonString = JsonSerializer.Serialize(saveData, new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true
|
|
});
|
|
File.WriteAllText(filePath, jsonString);
|
|
GD.Print($"Game saved successfully: {fileName}");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
GD.PrintErr($"Failed to save game: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public List<SaveData> GetSavedGames()
|
|
{
|
|
var savedGames = new List<SaveData>();
|
|
|
|
if (!Directory.Exists(_saveDirectory))
|
|
return savedGames;
|
|
|
|
try
|
|
{
|
|
var saveFiles = Directory.GetFiles(_saveDirectory, "*.json");
|
|
|
|
foreach (string filePath in saveFiles)
|
|
{
|
|
try
|
|
{
|
|
string jsonString = File.ReadAllText(filePath);
|
|
var saveData = JsonSerializer.Deserialize<SaveData>(jsonString);
|
|
if (saveData != null)
|
|
{
|
|
savedGames.Add(saveData);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
GD.PrintErr($"Failed to load save file {filePath}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
// Sortera efter datum (nyast först)
|
|
savedGames.Sort((a, b) => b.SaveDate.CompareTo(a.SaveDate));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
GD.PrintErr($"Failed to read saves directory: {ex.Message}");
|
|
}
|
|
|
|
return savedGames;
|
|
}
|
|
|
|
public bool LoadGame(SaveData saveData)
|
|
{
|
|
try
|
|
{
|
|
GameState.LoadedGameTime = saveData.GameTime;
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
GD.PrintErr($"Failed to load game: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
} |