feat: implement game saving and loading in TicTacToe

- Add serialization support to `World`, `EntityAllocator`, and
  `SparseSet`
- Implement `SaveGame` and `LoadGame` functionality in the TicTacToe
  example
- Add ability to resume a game from a saved state
- Implement auto-save after every move in the game loop
This commit is contained in:
2026-07-18 21:06:57 +08:00
parent a19861c080
commit 0a28890f2c
5 changed files with 124 additions and 48 deletions
@@ -38,9 +38,9 @@ public struct PlaceMarkCommand : ICommand
if (target == null)
return; // Cell already occupied or invalid position.
// Place the mark.
// Place the mark. ComponentAdded is sufficient — MarkModified
// is only needed when mutating an existing component via GetComponent<T>.
world.AddComponent(target.Value, new Mark { Player = state.CurrentPlayer });
world.MarkModified<Mark>(target.Value);
// Advance turn.
state.MoveCount++;
+80 -46
View File
@@ -5,58 +5,47 @@ namespace TicTacToe;
public static class Program
{
private static readonly string SavePath = Path.Combine(
AppContext.BaseDirectory, "save.bin");
public static void Main()
{
var world = new World();
// ── Setup reactivity logging ──────────────────────────────────
//
// Each subscription appends to a shared log buffer. The log is
// printed after the board render so Console.Clear() doesn't wipe it.
var reactivityLog = new List<string>();
SetupReactivityLogging(world, reactivityLog);
// 1. Log every entity-level change (creates, destroys).
world.ObserveEntityChanges().Subscribe(change =>
// ── Try to load a saved game ──────────────────────────────────
bool loaded = false;
if (File.Exists(SavePath))
{
if (change.ComponentType != null) return;
reactivityLog.Add($"[react] {change}");
});
Console.Write("Saved game found. Load it? (y/n): ");
if (Console.ReadLine()?.Trim().ToLower() == "y")
{
using var stream = File.OpenRead(SavePath);
WorldSerializer.Load(world, stream);
loaded = true;
Console.WriteLine("Game loaded!");
Console.WriteLine();
}
}
// 2. Log every Mark component change (placed on a cell).
world.ObserveComponentChanges<Mark>().Subscribe(change =>
// ── Load fresh board from CSV (if not loaded) ─────────────────
if (!loaded)
{
reactivityLog.Add($"[react] {change}");
});
var csvPath = Path.Combine(AppContext.BaseDirectory, "Data", "board.csv");
CsvLoader.LoadCells(world, csvPath);
world.PostChanges();
// 3. Log every GameState singleton change.
world.ObserveComponentChanges<GameState>().Subscribe(change =>
{
reactivityLog.Add($"[react] {change}");
});
// 4. Log changes matching a query: cells that have a Mark.
var markedQuery = world.Query().With<Cell>().With<Mark>().Build();
world.ObserveQuery(markedQuery).Subscribe(change =>
{
reactivityLog.Add($"[react:query] {change}");
});
// ── Load initial state from CSV ───────────────────────────────
var csvPath = Path.Combine(AppContext.BaseDirectory, "Data", "board.csv");
CsvLoader.LoadCells(world, csvPath);
world.PostChanges(); // flush entity-created notifications
// ── Initialize singleton ──────────────────────────────────────
world.SetSingleton(new GameState
{
CurrentPlayer = Player.X,
Status = GameStatus.Playing,
MoveCount = 0
});
world.PostChanges();
world.SetSingleton(new GameState
{
CurrentPlayer = Player.X,
Status = GameStatus.Playing,
MoveCount = 0
});
world.PostChanges();
}
// ── Wire up systems ───────────────────────────────────────────
@@ -66,7 +55,6 @@ public static class Program
// ── Game loop ─────────────────────────────────────────────────
// Initial render.
group.RunLogical();
PrintReactivityLog(reactivityLog);
@@ -80,12 +68,20 @@ public static class Program
if (string.IsNullOrWhiteSpace(input))
continue;
// "save" command.
if (input.Trim().ToLower() == "save")
{
SaveGame(world);
Console.WriteLine(" Game saved.");
continue;
}
var parts = input.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2 ||
!int.TryParse(parts[0], out var row) ||
!int.TryParse(parts[1], out var col))
{
Console.WriteLine(" Invalid input. Try \"1 2\".");
Console.WriteLine(" Invalid input. Try \"1 2\" or \"save\".");
continue;
}
@@ -98,6 +94,9 @@ public static class Program
world.Commands.Enqueue(new PlaceMarkCommand { Row = row, Col = col });
group.RunLogical();
PrintReactivityLog(reactivityLog);
// Auto-save after every move.
SaveGame(world);
}
// ── Final state ───────────────────────────────────────────────
@@ -105,6 +104,41 @@ public static class Program
Console.WriteLine();
Console.WriteLine("=== Game over ===");
PrintReactivityLog(reactivityLog);
// Clean up save file on game over.
if (File.Exists(SavePath))
File.Delete(SavePath);
}
private static void SaveGame(World world)
{
using var stream = File.Create(SavePath);
WorldSerializer.Save(world, stream);
}
private static void SetupReactivityLogging(World world, List<string> log)
{
world.ObserveEntityChanges().Subscribe(change =>
{
if (change.ComponentType != null) return;
log.Add($"[react] {change}");
});
world.ObserveComponentChanges<Mark>().Subscribe(change =>
{
log.Add($"[react] {change}");
});
world.ObserveComponentChanges<GameState>().Subscribe(change =>
{
log.Add($"[react] {change}");
});
var markedQuery = world.Query().With<Cell>().With<Mark>().Build();
world.ObserveQuery(markedQuery).Subscribe(change =>
{
log.Add($"[react:query] {change}");
});
}
private static void PrintReactivityLog(List<string> log)
@@ -116,4 +150,4 @@ public static class Program
Console.WriteLine();
log.Clear();
}
}
}