Skip to content

Chapter 16: Profiles, Settings and Saving ​

In Chapter 15: Powerups, you finished the rules of play. The game now ends a run, but it forgets everything the moment the window closes. The HI: figure on the HUD is always 0, because nothing stores a best score.

In this chapter, you make the game remember. You add a profile, a small record of the high score, the unlocked levels, the player's settings and some lifetime statistics. You save it to a file without risking the old copy, and you only save between screens, never during a level.

Figure 16-1: The chapter 16 result. The HUD shows the best score, and the same number is stored in the profile file
Figure 16-1: The chapter 16 result. The HUD shows the best score, and the same number is stored in the profile file. This is a drawn illustration, not a screenshot.

Time: [TODO Simon: time estimate for chapter 16]

In this chapter, you will:

  • Learn where a desktop game should keep its save file on Windows, Linux and macOS.
  • Build ProfileStorage, with a save that cannot corrupt the old file and a load that survives a bad one.
  • Build ProfileTracker, which owns the rules for what each game event means to the profile.
  • Connect the profile to the event stream, so no rule of play touches it.
  • Save only between scenes and when the game closes, never in the middle of a level.

Requirements in this chapter ​

IDShort name
PRO-01The profile is a JSON file in the local application data folder
PRO-02A missing or corrupt profile loads as a fresh one
PRO-03Saving writes a temporary file and swaps it in
PRO-04A failed save returns false and is not retried every frame
PRO-05Saved between scenes and on exit, never during play
PRO-06Clearing a level unlocks the next
PRO-07Lifetime statistics
PRO-08Settings are saved with the profile
SCO-07The high score
NFR-02No disk IO during a level

Where saves live ​

A game must not save next to its own program files. That folder may be read-only, and an update may replace it. Each operating system has a folder for data that belongs to one user, and .NET reaches it through Environment.SpecialFolder.LocalApplicationData. The game adds a LastPerimeter folder inside it and keeps one file there, profile.json. Figure 16-2 shows the three paths and the moments at which the game touches the file.

Figure 16-2: Where profile.json lives on each system, and when the game loads and saves it
Figure 16-2: Where profile.json lives on each system, and when the game loads and saves it

The file is plain JSON, so you can open it in a text editor to check what the game stored. You do that at the end of the chapter.

Atomic saves ​

Writing a file is not instant. If the power fails or the process is killed halfway through, the file holds half of the new text and none of the old. The next load then finds broken JSON, and the player has lost everything.

An atomic operation either happens completely or not at all. ProfileStorage.Save gets that effect in two steps. It writes the whole profile to a temporary file next to the real one, named profile.json.tmp. Only when that write has finished does it move the temporary file over the real one. A move within one folder is a single step for the file system, so a crash leaves either the old profile or the new one, never a mixture.

Catching what you expect ​

Loading can fail for reasons the game expects. The file may be missing, locked by another program or hand-edited into invalid JSON. In each case the right answer is a fresh profile, so the game still starts. The code catches exactly those failures: IOException, UnauthorizedAccessException and JsonException.

It does not use a bare catch. A bare catch also swallows a bug, for example a null reference in your own code. The game then starts quietly with a blank profile, and the real cause stays hidden. Catching only the expected errors means an unexpected one still shows up as a crash, where you can see it.

NOTE

Save catches IOException and UnauthorizedAccessException only. It never reads JSON, so JsonException cannot happen there.

Rules about the profile ​

Clearing level 3 to unlock level 4 is a rule about the profile. If you write it at the place where the level ends, every other place that ends a level needs its own copy, and the copies drift apart. So the rule lives in one class, ProfileTracker. The rest of the game only reports what happened, for example "level 3 was cleared", and the tracker decides what that means.

The tracker also remembers whether the profile has changed since the last save. That flag is called dirty. Every Record operation sets it. SaveIfDirty writes the file only when it is set, and then clears it.

When to save ​

A disk write can take a few milliseconds, and sometimes much longer. During a level, one slow write would show as a stutter. The game therefore saves only at two moments. The first is any frame in which the top scene allows saving, which is every scene except GameplayScene. The second is when the game closes. The dirty flag collects every change made during a level, and the file is written once the level screen is gone.

The scene decides, through a property you added in Chapter 05, AllowsSaving. The scene manager passes the answer on as CanSave, and the host asks it once per frame.

Setting up the data ​

The profile is three plain data classes and one enum. The first listing is for the settings, so you start with the enum. GameSettings needs a ThemePreset, and Chapter 20 makes the themes work.

Open Source/Data/Enums.cs. Add the following enum to the end of the file, below the last enum:

add-type Source/Data/Enums.cs
csharp
public enum ThemePreset
{
    NeonVector,
    CrtGreen,
    SunsetSynth,
}

In the Source/Data folder, create a new file named GameSettings.cs and add the following code. It holds every setting the options screen of Chapter 17 changes. The defaults are the settings a new player gets.

new-file Source/Data/GameSettings.cs
csharp
namespace LastPerimeter.Data;

public sealed class GameSettings
{
    public DifficultyPreset Difficulty { get; set; } = DifficultyPreset.Classic;
    public ThemePreset Theme { get; set; } = ThemePreset.NeonVector;
    public bool ColorblindMode { get; set; }
    public bool AudioEnabled { get; set; } = true;
    public float MasterVolume { get; set; } = 1f;
    public float UiScale { get; set; } = 1f;
    public bool ReducedFlash { get; set; }
    public bool TutorialCompleted { get; set; }
}

In the Source/Data folder, create a new file named PlayerStatistics.cs and add the following code. These are lifetime counters. HighestLevelReached starts at 1, because every player has reached level 1.

new-file Source/Data/PlayerStatistics.cs
csharp
namespace LastPerimeter.Data;

public sealed class PlayerStatistics
{
    public int TotalRunsPlayed { get; set; }
    public int TotalDeaths { get; set; }
    public int TotalLevelsCleared { get; set; }
    public int HighestLevelReached { get; set; } = 1;
    public int TotalPowerupsCollected { get; set; }
    public int TotalCapturesCompleted { get; set; }
    public int BestDailyChallengeScore { get; set; }
}

In the Source/Data folder, create a new file named PlayerProfile.cs and add the following code. It ties the other two together with the high score and the highest unlocked level.

new-file Source/Data/PlayerProfile.cs
csharp
namespace LastPerimeter.Data;

public sealed class PlayerProfile
{
    public int HighScore { get; set; }
    public int HighestUnlockedLevel { get; set; } = 1;
    public GameSettings Settings { get; set; } = new();
    public PlayerStatistics Statistics { get; set; } = new();
}

The key things to note are:

  • Every property has a public setter. The JSON serialiser needs one to fill the object when it loads a file.
  • A property that is missing from an old save file keeps its default. This is why a profile written by an older version still loads.
  • HighestUnlockedLevel starts at 1, so a new player can always play level 1.

Building the storage service ​

ProfileStorage reads and writes the file and does nothing else. It never decides what a profile contains. Its constructor takes an optional path. A test passes a path in a temporary folder. The game passes nothing and gets the real location from Figure 16-2.

IMPORTANT

Every test in this chapter uses a temporary folder with a unique name, and deletes it afterwards. No test touches your real profile. If you already have a saved profile from playing, it is safe while the tests run.

Your first listing is the shell of the class. The constructor is written in full, and Load and Save throw. In the Source/Systems folder, create a new file named ProfileStorage.cs and add the following code:

new-file Source/Systems/ProfileStorage.cs
csharp
using System.Text.Json;
using LastPerimeter.Data;

namespace LastPerimeter.Systems;

public sealed class ProfileStorage
{
    private static readonly JsonSerializerOptions SerializerOptions = new() { WriteIndented = true };
    private readonly string _profilePath;

    public ProfileStorage(string? profilePath = null)
    {
        _profilePath = profilePath ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LastPerimeter", "profile.json");
    }

    public PlayerProfile Load()
    {
        throw new NotImplementedException();
    }

    public bool Save(PlayerProfile profile)
    {
        throw new NotImplementedException();
    }
}

The key things to note are:

  • With no argument, the constructor builds the path from LocalApplicationData, the folder LastPerimeter and the file name profile.json. This is PRO-01.
  • SerializerOptions turns on indented output, so the file is readable in a text editor.
  • The two operations throw NotImplementedException for now, which keeps the project compiling.

Loading a profile ​

ProfileStorage.Load() : PlayerProfile

  • Takes: nothing.
  • Gives: the stored profile.
  • Promises: a missing file gives a fresh profile with default values.
  • Refuses: a corrupt file does not throw. It also gives a fresh profile.
  • Requirements: PRO-02.

In the Tests/Systems folder, create a new file named ProfileStorageTests.cs and add the following code. It holds the first test, and a Dispose method that deletes the temporary folder after each test. The class implements IDisposable, and xUnit calls Dispose after every test. New to IDisposable? See the C# primer.

new-file Tests/Systems/ProfileStorageTests.cs
csharp
using LastPerimeter.Data;
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class ProfileStorageTests : IDisposable
{
    private readonly string _profilePath = Path.Combine(Path.GetTempPath(), $"lastperimeter-profile-tests-{Guid.NewGuid():N}", "profile.json");

    [Fact]
    public void Load_ReturnsDefaultProfile_WhenFileDoesNotExist()
    {
        ProfileStorage storage = new(_profilePath);

        PlayerProfile profile = storage.Load();

        Assert.Equal(0, profile.HighScore);
        Assert.Equal(1, profile.HighestUnlockedLevel);
    }

    public void Dispose()
    {
        string? directory = Path.GetDirectoryName(_profilePath);
        if (directory is not null && Directory.Exists(directory))
        {
            Directory.Delete(directory, recursive: true);
        }
    }
}

Open Tests/Systems/ProfileStorageTests.cs. Add the following test to the ProfileStorageTests class, below the Load_ReturnsDefaultProfile_WhenFileDoesNotExist test. It writes text that is not JSON where the profile should be.

add-member Tests/Systems/ProfileStorageTests.cs after=Load_ReturnsDefaultProfile_WhenFileDoesNotExist
csharp
    [Fact]
    public void Load_ReturnsDefaultProfile_WhenFileIsCorrupt()
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_profilePath)!);
        File.WriteAllText(_profilePath, "{ this is not valid json");
        ProfileStorage storage = new(_profilePath);

        PlayerProfile profile = storage.Load();

        Assert.Equal(0, profile.HighScore);
        Assert.Equal(1, profile.HighestUnlockedLevel);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 2 and Passed: 115. The 115 passes are the tests from earlier chapters, and the two failures are your new tests, which hit the stub.

Open Source/Systems/ProfileStorage.cs. Find the Load method and replace the whole method with the following:

replace-method Source/Systems/ProfileStorage.cs Load
csharp
    public PlayerProfile Load()
    {
        if (!File.Exists(_profilePath))
        {
            return new PlayerProfile();
        }

        try
        {
            string json = File.ReadAllText(_profilePath);
            return JsonSerializer.Deserialize<PlayerProfile>(json, SerializerOptions) ?? new PlayerProfile();
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
        {
            // Only file and format failures fall back to a fresh profile.
            // Programming errors still surface.
            return new PlayerProfile();
        }
    }

Run dotnet test again from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 117.

The key things to note are:

  • The method checks File.Exists first, so the common case of a first run costs no exception.
  • The catch has a when filter, so only the three expected exception types are caught. Anything else passes through. New to when? See the C# primer.
  • JsonSerializer.Deserialize can return null for the text null, so the ?? gives a fresh profile in that case too.

Saving a profile ​

ProfileStorage.Save(profile) : bool

  • Takes: a profile.
  • Gives: true when the file was written.
  • Promises: the write goes to a temporary file first, which is then moved over the real file. No .tmp file is left behind. A save followed by a load gives back the same values.
  • Refuses: a folder that cannot be created, or a file that cannot be written, gives false. It never throws.
  • Requirements: PRO-01, PRO-03, PRO-04, PRO-08.

Open Tests/Systems/ProfileStorageTests.cs. Add the following test to the ProfileStorageTests class, below the Load_ReturnsDefaultProfile_WhenFileDoesNotExist test. It saves a profile with some changed values, loads it again and compares them, including ReducedFlash, which proves that settings travel with the profile (PRO-08).

add-member Tests/Systems/ProfileStorageTests.cs after=Load_ReturnsDefaultProfile_WhenFileDoesNotExist
csharp
    [Fact]
    public void SaveThenLoad_RoundTripsProfileValues()
    {
        ProfileStorage storage = new(_profilePath);
        PlayerProfile saved = new()
        {
            HighScore = 12500,
            HighestUnlockedLevel = 7,
        };
        saved.Settings.ReducedFlash = true;
        saved.Settings.Difficulty = DifficultyPreset.Hardcore;
        saved.Statistics.TotalRunsPlayed = 3;

        storage.Save(saved);
        PlayerProfile loaded = storage.Load();

        Assert.Equal(12500, loaded.HighScore);
        Assert.Equal(7, loaded.HighestUnlockedLevel);
        Assert.True(loaded.Settings.ReducedFlash);
        Assert.Equal(DifficultyPreset.Hardcore, loaded.Settings.Difficulty);
        Assert.Equal(3, loaded.Statistics.TotalRunsPlayed);
    }

Add the following test below the Load_ReturnsDefaultProfile_WhenFileIsCorrupt test. It puts a file where the profile folder should be, so the folder cannot be created.

add-member Tests/Systems/ProfileStorageTests.cs after=Load_ReturnsDefaultProfile_WhenFileIsCorrupt
csharp
    [Fact]
    public void Save_ReturnsFalse_WhenProfileFolderCannotBeCreated()
    {
        // A file where the profile folder should be makes the folder impossible to create.
        string folder = Path.GetDirectoryName(_profilePath)!;
        Directory.CreateDirectory(Path.GetDirectoryName(folder)!);
        File.WriteAllText(folder, "not a folder");
        ProfileStorage storage = new(_profilePath);

        bool saved = storage.Save(new PlayerProfile());
        File.Delete(folder);

        Assert.False(saved);
    }

Add the following test below the Save_ReturnsFalse_WhenProfileFolderCannotBeCreated test. It checks that the file exists after a save and that the temporary file does not.

add-member Tests/Systems/ProfileStorageTests.cs after=Save_ReturnsFalse_WhenProfileFolderCannotBeCreated
csharp
    [Fact]
    public void Save_LeavesNoTemporaryFile()
    {
        ProfileStorage storage = new(_profilePath);

        Assert.True(storage.Save(new PlayerProfile { HighScore = 10 }));

        Assert.True(File.Exists(_profilePath));
        Assert.False(File.Exists(_profilePath + ".tmp"));
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 3 and Passed: 117. Each new test calls Save, which still throws.

Open Source/Systems/ProfileStorage.cs. Find the Save method and replace the whole method with the following:

replace-method Source/Systems/ProfileStorage.cs Save
csharp
    // Returns false when the file cannot be written, so a locked or read-only
    // profile never crashes the game.
    public bool Save(PlayerProfile profile)
    {
        string temporaryPath = _profilePath + ".tmp";
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(_profilePath)!);

            // Write a temporary file, then swap it in. A crash mid-write leaves
            // the previous profile intact instead of a corrupt one.
            File.WriteAllText(temporaryPath, JsonSerializer.Serialize(profile, SerializerOptions));
            File.Move(temporaryPath, _profilePath, overwrite: true);
            return true;
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
        {
            return false;
        }
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 120.

The key things to note are:

  • File.Move with overwrite: true is the swap. The write to the temporary file comes first, so a failure there leaves the real file untouched.
  • Directory.CreateDirectory does nothing when the folder exists, so the first save creates LastPerimeter and later saves reuse it.
  • The catch names only IOException and UnauthorizedAccessException. The folder test hits the first, because a file already holds the folder's name.
  • Even when a save fails, a half-written .tmp file can remain. The next successful save overwrites it.

Building the profile tracker ​

ProfileTracker holds the live profile while the game runs and applies the rules. Its shell has the constructor and three properties written in full. Profile is the current profile, Settings is a shortcut to its settings, and IsDirty tells whether a save is pending.

In the Source/Systems folder, create a new file named ProfileTracker.cs and add the following code. Each operation throws for now:

new-file Source/Systems/ProfileTracker.cs
csharp
using LastPerimeter.Data;

namespace LastPerimeter.Systems;

// Owns the player's profile while the game runs: the lifetime statistics, the
// unlock and high-score rules, and when the profile is written to disk. The app
// reports what happened; this class decides what that means for the profile.
public sealed class ProfileTracker
{
    private readonly ProfileStorage _storage;

    public ProfileTracker(ProfileStorage storage)
    {
        _storage = storage;
    }

    public PlayerProfile Profile { get; private set; } = new();
    public GameSettings Settings => Profile.Settings;
    public bool IsDirty { get; private set; }

    public void Load()
    {
        throw new NotImplementedException();
    }

    public void RecordRunStarted()
    {
        throw new NotImplementedException();
    }

    public void RecordPowerupCollected()
    {
        throw new NotImplementedException();
    }

    public void RecordCapture()
    {
        throw new NotImplementedException();
    }

    public void RecordLevelCleared(int level)
    {
        throw new NotImplementedException();
    }

    public void RecordDeath()
    {
        throw new NotImplementedException();
    }

    public void RecordRunFinished(int score, bool dailyChallenge = false)
    {
        throw new NotImplementedException();
    }

    public void CompleteTutorial()
    {
        throw new NotImplementedException();
    }

    public void MarkSettingsChanged()
    {
        throw new NotImplementedException();
    }

    public bool SaveIfDirty()
    {
        throw new NotImplementedException();
    }
}

You build the operations in three groups, each with its tests first. The test file is created with the first group.

Unlocks and the high score ​

ProfileTracker.RecordLevelCleared(level) : void

  • Takes: the number of the level that was cleared.
  • Gives: nothing. The profile changes.
  • Promises: the next level is unlocked, the cleared count goes up, and the highest level reached is kept. The profile becomes dirty.
  • Refuses: replaying an old level never lowers HighestUnlockedLevel.
  • Requirements: PRO-06, PRO-07.

ProfileTracker.RecordRunFinished(score, dailyChallenge) : void

  • Takes: the final score of a run, and whether it was a daily challenge.
  • Gives: nothing. The profile changes.
  • Promises: the high score becomes the larger of the old value and the new score. A daily run also updates the best daily score. The profile becomes dirty.
  • Refuses: a lower score never replaces a higher one.
  • Requirements: SCO-07, PRO-07.

In the Tests/Systems folder, create a new file named ProfileTrackerTests.cs and add the following code. It holds the unlock test and the same Dispose pattern as before. Each test gets its own temporary profile path.

new-file Tests/Systems/ProfileTrackerTests.cs
csharp
using LastPerimeter.Systems;

namespace LastPerimeter.Tests.Systems;

public sealed class ProfileTrackerTests : IDisposable
{
    private readonly string _profilePath = Path.Combine(Path.GetTempPath(), $"lastperimeter-tracker-tests-{Guid.NewGuid():N}", "profile.json");

    [Fact]
    public void RecordLevelCleared_UnlocksNextLevel()
    {
        ProfileTracker tracker = new(new ProfileStorage(_profilePath));

        tracker.RecordLevelCleared(3);

        Assert.Equal(4, tracker.Profile.HighestUnlockedLevel);
        Assert.Equal(1, tracker.Profile.Statistics.TotalLevelsCleared);
        Assert.Equal(3, tracker.Profile.Statistics.HighestLevelReached);
        Assert.True(tracker.IsDirty);
    }

    public void Dispose()
    {
        string? directory = Path.GetDirectoryName(_profilePath);
        if (directory is not null && Directory.Exists(directory))
        {
            Directory.Delete(directory, recursive: true);
        }
    }
}

Open Tests/Systems/ProfileTrackerTests.cs. Add the following test to the ProfileTrackerTests class, below the RecordLevelCleared_UnlocksNextLevel test. It records a score of 5000 and then a lower score of 1200.

add-member Tests/Systems/ProfileTrackerTests.cs after=RecordLevelCleared_UnlocksNextLevel
csharp
    [Fact]
    public void RecordRunFinished_KeepsTheHigherScore()
    {
        ProfileTracker tracker = new(new ProfileStorage(_profilePath));

        tracker.RecordRunFinished(5000);
        tracker.RecordRunFinished(1200);

        Assert.Equal(5000, tracker.Profile.HighScore);
    }

Add the following test below the RecordRunFinished_KeepsTheHigherScore test. It checks that a normal run leaves the daily best alone, and that a daily run sets it.

add-member Tests/Systems/ProfileTrackerTests.cs after=RecordRunFinished_KeepsTheHigherScore
csharp
    [Fact]
    public void RecordRunFinished_UpdatesDailyBestOnlyForDailyRuns()
    {
        ProfileTracker tracker = new(new ProfileStorage(_profilePath));

        tracker.RecordRunFinished(800);
        Assert.Equal(0, tracker.Profile.Statistics.BestDailyChallengeScore);

        tracker.RecordRunFinished(600, dailyChallenge: true);
        Assert.Equal(600, tracker.Profile.Statistics.BestDailyChallengeScore);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 3 and Passed: 120.

Open Source/Systems/ProfileTracker.cs. Find the RecordLevelCleared method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordLevelCleared
csharp
    public void RecordLevelCleared(int level)
    {
        Profile.HighestUnlockedLevel = Math.Max(Profile.HighestUnlockedLevel, level + 1);
        Profile.Statistics.TotalLevelsCleared++;
        Profile.Statistics.HighestLevelReached = Math.Max(Profile.Statistics.HighestLevelReached, level);
        IsDirty = true;
    }

Find the RecordRunFinished method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordRunFinished
csharp
    // The daily flag is used from chapter 19, where daily challenges arrive.
    public void RecordRunFinished(int score, bool dailyChallenge = false)
    {
        Profile.HighScore = Math.Max(Profile.HighScore, score);
        if (dailyChallenge)
        {
            Profile.Statistics.BestDailyChallengeScore = Math.Max(Profile.Statistics.BestDailyChallengeScore, score);
        }

        IsDirty = true;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 123.

The key things to note are:

  • Math.Max does the work in both operations. Taking the larger of the old and new value means an order of events can never lower a record.
  • RecordLevelCleared unlocks level + 1. Clearing level 3 sets HighestUnlockedLevel to 4, which is what the test checks.
  • The dailyChallenge parameter has a default of false, so the call in this chapter passes one argument. Chapter 19 passes true for a daily run.

Counting events ​

Four operations only count. Each adds one to a counter and marks the profile dirty.

ProfileTracker.RecordRunStarted(), RecordCapture(), RecordDeath() and RecordPowerupCollected() : void

  • Takes: nothing.
  • Gives: nothing. The profile changes.
  • Promises: the matching counter in Statistics goes up by one, and the profile becomes dirty.
  • Refuses: nothing.
  • Requirements: PRO-07.

Open Tests/Systems/ProfileTrackerTests.cs. Add the following test to the ProfileTrackerTests class, below the Dispose method. It calls each operation and checks the four counters, with two captures so the test shows that a count adds up.

add-member Tests/Systems/ProfileTrackerTests.cs at=end
csharp
    [Fact]
    public void RecordedEvents_RaiseTheirCounters()
    {
        ProfileTracker tracker = new(new ProfileStorage(_profilePath));

        tracker.RecordRunStarted();
        tracker.RecordCapture();
        tracker.RecordCapture();
        tracker.RecordDeath();
        tracker.RecordPowerupCollected();

        Assert.Equal(1, tracker.Profile.Statistics.TotalRunsPlayed);
        Assert.Equal(2, tracker.Profile.Statistics.TotalCapturesCompleted);
        Assert.Equal(1, tracker.Profile.Statistics.TotalDeaths);
        Assert.Equal(1, tracker.Profile.Statistics.TotalPowerupsCollected);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 123.

Open Source/Systems/ProfileTracker.cs. Find the RecordRunStarted method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordRunStarted
csharp
    public void RecordRunStarted()
    {
        Profile.Statistics.TotalRunsPlayed++;
        IsDirty = true;
    }

Find the RecordPowerupCollected method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordPowerupCollected
csharp
    public void RecordPowerupCollected()
    {
        Profile.Statistics.TotalPowerupsCollected++;
        IsDirty = true;
    }

Find the RecordCapture method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordCapture
csharp
    public void RecordCapture()
    {
        Profile.Statistics.TotalCapturesCompleted++;
        IsDirty = true;
    }

Find the RecordDeath method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs RecordDeath
csharp
    public void RecordDeath()
    {
        Profile.Statistics.TotalDeaths++;
        IsDirty = true;
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 124.

The key things to note are:

  • The four bodies differ only in the counter they raise. Keeping them as four small operations means a call site says what happened, and not which number to change.
  • Every operation sets IsDirty, so the host knows a save is due. The counters themselves are not written to disk until SaveIfDirty runs.

Loading and saving through the tracker ​

The last group connects the tracker to the storage service.

ProfileTracker.SaveIfDirty() : bool

  • Takes: nothing.
  • Gives: true when a save was attempted and succeeded.
  • Promises: the file is written only when the profile is dirty. The dirty flag is cleared before the write.
  • Refuses: a clean profile gives false and does not touch the disk. A failed write is not retried until the next change.
  • Requirements: PRO-04.

ProfileTracker.Load(), CompleteTutorial() and MarkSettingsChanged() : void are short. Load replaces the live profile with the stored one and clears the dirty flag. CompleteTutorial sets TutorialCompleted, which Chapter 17 uses. MarkSettingsChanged sets the dirty flag after the options screen changes a setting. Requirements: PRO-08.

Open Tests/Systems/ProfileTrackerTests.cs. Add the following test to the ProfileTrackerTests class, below the RecordRunFinished_UpdatesDailyBestOnlyForDailyRuns test. It saves once, saves again and then loads the file with a second tracker.

add-member Tests/Systems/ProfileTrackerTests.cs after=RecordRunFinished_UpdatesDailyBestOnlyForDailyRuns
csharp
    [Fact]
    public void SaveIfDirty_WritesOnceThenReportsClean()
    {
        ProfileTracker tracker = new(new ProfileStorage(_profilePath));
        tracker.RecordCapture();

        Assert.True(tracker.SaveIfDirty());
        Assert.False(tracker.IsDirty);
        Assert.False(tracker.SaveIfDirty());

        ProfileTracker reloaded = new(new ProfileStorage(_profilePath));
        reloaded.Load();
        Assert.Equal(1, reloaded.Profile.Statistics.TotalCapturesCompleted);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 124.

Open Source/Systems/ProfileTracker.cs. Find the Load method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs Load
csharp
    public void Load()
    {
        Profile = _storage.Load();
        IsDirty = false;
    }

Find the CompleteTutorial method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs CompleteTutorial
csharp
    public void CompleteTutorial()
    {
        Settings.TutorialCompleted = true;
        IsDirty = true;
    }

Find the MarkSettingsChanged method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs MarkSettingsChanged
csharp
    public void MarkSettingsChanged()
    {
        IsDirty = true;
    }

Find the SaveIfDirty method and replace the whole method with the following:

replace-method Source/Systems/ProfileTracker.cs SaveIfDirty
csharp
    // Returns true when a save was attempted and succeeded. A failed save is not
    // retried every frame: the next change marks the profile dirty again.
    public bool SaveIfDirty()
    {
        if (!IsDirty)
        {
            return false;
        }

        IsDirty = false;
        return _storage.Save(Profile);
    }

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 125.

The key things to note are:

  • SaveIfDirty clears IsDirty before it saves. If the disk refuses, the flag stays clear, so the next frame does not try again. The next real change sets it, and that is one attempt per change instead of sixty a second.
  • The second call in the test returns false, because nothing changed since the first save. This proves that a clean profile costs no disk write.
  • Only the Statistics.TotalCapturesCompleted check goes through the file. A second tracker with the same path reads what the first wrote, which proves the data reached the disk.
  • Load clears IsDirty, because a profile that has just been read matches the file.

Saving only between scenes ​

The host asks the scene manager whether it may save. The manager answers with the top scene's AllowsSaving, or true when there is no scene. The base Scene class already says true. Only GameplayScene will say false.

SceneManager.CanSave : bool

  • Takes: nothing.
  • Gives: the top scene's AllowsSaving, or true when the stack is empty.
  • Promises: it is false while a gameplay scene is on top, and true again after the scene changes.
  • Refuses: nothing.
  • Requirements: PRO-05, NFR-02.

Open Source/Scenes/SceneManager.cs. Add the following property to the SceneManager class, below the Count property. It throws for now, so the test can fail first.

add-member Source/Scenes/SceneManager.cs after=Count
csharp
    // The top scene decides whether the profile may be written this frame.
    public bool CanSave => throw new NotImplementedException();

Open Tests/Scenes/SceneManagerTests.cs. The test needs a stub scene that can say no to saving. Add the following property to the StubScene class, below the Updates property:

add-member Tests/Scenes/SceneManagerTests.cs after=Updates type=StubScene
csharp
        public bool Saving { get; init; } = true;

In the StubScene class, add the following property above the Update method. It tells the scene manager the answer that Saving holds.

add-member Tests/Scenes/SceneManagerTests.cs before=Update type=StubScene
csharp
        public override bool AllowsSaving => Saving;

Add the following test to the SceneManagerTests class, at the end of the class. It starts on a scene that refuses saving, changes to one that allows it and checks CanSave each time.

add-member Tests/Scenes/SceneManagerTests.cs at=end
csharp
    [Fact]
    public void SaveHook_NeverRunsDuringGameplay()
    {
        StubScene gameplay = new() { Saving = false };
        StubScene menu = new();
        SceneManager manager = StartWith(gameplay);
        Assert.False(manager.CanSave);

        manager.Change(menu);
        manager.Update(0.016f, InputState.Empty);

        Assert.True(manager.CanSave);
    }

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 1 and Passed: 125.

Open Source/Scenes/SceneManager.cs. Find the CanSave property and replace the whole property with the following:

replace-method Source/Scenes/SceneManager.cs CanSave
csharp
    // The top scene decides whether the profile may be written this frame.
    public bool CanSave => Top?.AllowsSaving ?? true;

Run dotnet test from the LastPerimeter folder. The summary line should report Failed: 0 and Passed: 126.

The key things to note are:

  • Top?.AllowsSaving ?? true reads as "the top scene's answer, or yes when there is no scene". New to ?. and ??? See the C# primer.
  • The test calls manager.Update after the change, because a change takes effect only after an update. Chapter 05 explained why.
  • The test proves the hook, which is the manager's answer. The next section makes GameplayScene give the answer false and makes the host act on CanSave.

Wiring it into the game ​

Four files change. The shared services gain the tracker, the host loads and saves it, the gameplay scene reports what happens, and the HUD loses one stale comment. The host also keeps the smoke run away from your real profile. The simulation does not change. The profile is not a rule of play, and keeping it out of the simulation lets the simulation run in a test with no file system.

The shared services ​

Open Source/Game/GameServices.cs. In the GameServices class, find this line:

find Source/Game/GameServices.cs type=GameServices
csharp
    public AudioCuePlayer Audio { get; }

Add the following property directly below it:

csharp
    public ProfileTracker Profile { get; }

In the same file, find the first line of the constructor:

find Source/Game/GameServices.cs type=GameServices
csharp
    public GameServices(GameConfig config, GraphicsDevice graphicsDevice, Action<string> setWindowTitle, Func<KeyboardState>? readKeyboard = null)

Replace it with the following lines. The constructor takes a ProfileTracker, between the graphics device and the window title action. The keyboard function from Chapter 13 stays last:

csharp
    public GameServices(
        GameConfig config,
        GraphicsDevice graphicsDevice,
        ProfileTracker profile,
        Action<string> setWindowTitle,
        Func<KeyboardState>? readKeyboard = null)

In the same constructor, find this line:

find Source/Game/GameServices.cs type=GameServices
csharp
        Audio = new AudioCuePlayer();

Add the following line directly below it. Every scene now reaches the tracker as services.Profile:

csharp
        Profile = profile;

The host builds the tracker, and not the services, because the host also needs it outside the scenes, to load and save.

The host ​

The host loads and saves the profile. It also decides where the profile lives, and that is where the smoke run needs care. Open Source/Game/LastPerimeterApp.cs. At the top of the file, add the following line below the other using lines:

add-using Source/Game/LastPerimeterApp.cs
csharp
using LastPerimeter.Systems;

Find the two comment lines above the LastPerimeterApp class:

find Source/Game/LastPerimeterApp.cs
csharp
// The thin MonoGame host. It builds the shared services, owns the scene manager
// and forwards Update and Draw. It handles the smoke-test exit.

Replace them with the following lines, so the comment mentions the new job:

csharp
// The thin MonoGame host. It builds the shared services, owns the scene manager,
// forwards Update and Draw, saves the profile and handles the smoke-test exit.

In the LastPerimeterApp class, find this field:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
    private readonly GameLaunchOptions _launchOptions;

Add the following field directly below it. It has no initialiser, because the constructor chooses the storage path from the launch options, and a field initialiser cannot read them:

csharp
    private readonly ProfileTracker _profile;

In the constructor, find this line:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
        _launchOptions = launchOptions ?? new GameLaunchOptions(null);

Add the following line directly below it. A normal run passes no path, so ProfileStorage uses the real location from Figure 16-2. The smoke run passes SmokeScript.ProfilePath, a file under the system temp folder. The smoke run must never write your real profile. It plays a scripted capture and exits. If it wrote the real file, every smoke run would add one run, one capture and a scripted score to your statistics. A build server would also write into a real user folder. The temp path leaves your profile alone:

csharp
        _profile = new(new ProfileStorage(_launchOptions.AutoExitAfter is null ? null : SmokeScript.ProfilePath));

In the same constructor, find this line:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
        _services = new Lazy<GameServices>(() => new GameServices(_config, GraphicsDevice, title => Window.Title = title,

Replace it with the following lines. The call passes _profile to GameServices, and the smoke keyboard line below it is unchanged:

csharp
        _services = new Lazy<GameServices>(() => new GameServices(
            _config,
            GraphicsDevice,
            _profile,
            title => Window.Title = title,

In the LoadContent method, find these lines:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
    protected override void LoadContent()
    {

Add the following line directly below them. It loads the profile before the first scene, so the title screen already has the stored profile:

csharp
        _profile.Load();

In the Update method, find these two lines:

find Source/Game/LastPerimeterApp.cs type=LastPerimeterApp
csharp
        _scenes.Update((float)gameTime.ElapsedGameTime.TotalSeconds, input);
        base.Update(gameTime);

Replace them with the following lines. The save runs after the scene update, and only when _scenes.CanSave is true:

csharp
        _scenes.Update((float)gameTime.ElapsedGameTime.TotalSeconds, input);

        // Save between screens, never mid-play: a disk write during gameplay can
        // hitch a frame. OnExiting saves anything still pending when the game closes.
        if (_scenes.CanSave)
        {
            _profile.SaveIfDirty();
        }

        base.Update(gameTime);

Add the following method to the LastPerimeterApp class, below the Draw method. It saves anything still pending when the player closes the window, including changes made during a level:

add-member Source/Game/LastPerimeterApp.cs after=Draw
csharp
    protected override void OnExiting(object sender, ExitingEventArgs args)
    {
        _profile.SaveIfDirty();
        base.OnExiting(sender, args);
    }

The gameplay scene ​

Open Source/Scenes/GameplayScene.cs. In the GameplayScene class, find the Enter method line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
    public override void Enter()

Replace it with the following lines. The new property is the one scene that says no, and the Enter line is the one you found:

csharp
    // Gameplay is the only scene that must not trigger a profile write.
    public override bool AllowsSaving => false;

    public override void Enter()

In the React method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
                _services.Audio.PlayClaim();

Add the following line directly below it. A capture is recorded:

csharp
                _services.Profile.RecordCapture();

In the same method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            case LifeLost:

Add the following line directly below it. A death is recorded:

csharp
                _services.Profile.RecordDeath();

In the same method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            case PowerupCollected:

Add the following line directly below it. A powerup is recorded:

csharp
                _services.Profile.RecordPowerupCollected();

In the same method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
            case LevelCleared cleared:

Add the following line directly below it. A cleared level is recorded, which unlocks the next level:

csharp
                _services.Profile.RecordLevelCleared(_simulation.Session.Level);

In the same method, find this comment line in the RunLost case:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
                // Chapter 18 shows a run summary here instead.

Replace it with the following lines. The final score is recorded, and this is where the high score is set:

csharp
                _services.Profile.RecordRunFinished(_simulation.Session.Score);

                // Chapter 18 shows a run summary here instead.

In the CreateSimulation method, find this line:

find Source/Scenes/GameplayScene.cs type=GameplayScene
csharp
        GameSession session = new() { Player = new Player() };

Replace it with the following lines. The start of a run is recorded, and the new session gets the stored high score. The HUD reads HighScore from the session. The seed parameter from Chapter 13 stays, so the smoke run still starts from seed 1:

csharp
        services.Profile.RecordRunStarted();
        GameSession session = new() { Player = new Player(), HighScore = services.Profile.Profile.HighScore };

The scene still never writes a file. It only marks the profile dirty. The host saves later, when CanSave allows it.

The HUD ​

The HUD already draws the high score. A comment in HudRenderer.Draw says it shows 0 until this chapter, and it is now wrong. Open Source/Rendering/HudRenderer.cs. In the Draw method, find this comment line:

find Source/Rendering/HudRenderer.cs type=HudRenderer
csharp
    // The high score shows 0 until chapter 16 loads it from the profile.

Delete that line.

Running the tests ​

In a terminal, from the LastPerimeter folder, run dotnet test. The summary line should report Failed: 0 and Passed: 126. The 126 tests are the 115 from earlier chapters, the 5 in ProfileStorageTests, the 5 in ProfileTrackerTests and the 1 new scene manager test.

TestProves
Load_ReturnsDefaultProfile_WhenFileDoesNotExistPRO-02
Load_ReturnsDefaultProfile_WhenFileIsCorruptPRO-02
SaveThenLoad_RoundTripsProfileValuesPRO-03, PRO-08
Save_LeavesNoTemporaryFilePRO-03
Save_ReturnsFalse_WhenProfileFolderCannotBeCreatedPRO-04
SaveIfDirty_WritesOnceThenReportsCleanPRO-04
RecordLevelCleared_UnlocksNextLevelPRO-06
RecordRunFinished_KeepsTheHigherScoreSCO-07
RecordRunFinished_UpdatesDailyBestOnlyForDailyRunsPRO-07
RecordedEvents_RaiseTheirCountersPRO-07
SaveHook_NeverRunsDuringGameplayPRO-05, NFR-02

PRO-01 has no test of its own, because a test must never touch the real location. You check it in the next section. PRO-08 is proved here for storage only: the settings survive a save and a load. Chapter 17 shows the options screen, and Chapter 20 applies the theme at start-up.

Running the game ​

Steps 1 to 5 need a window and a keyboard. The tests confirm the storage and tracker rules, and step 4 reads the file, so you can confirm the saved values without watching the screen.

From the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK. Press Enter on the title screen. The HUD shows HI:0, because there is no profile file yet.

  1. A capture. Hold the Right arrow along the top wall, then hold Down, Right and Up to draw a trail back to the wall. The score rises.
  2. Lose every life. Leave the wall, release every key and wait. The fuse burns along the trail and costs a life. Repeat this until the third life is gone. The game returns to the title screen, which is a scene that allows saving, so the profile is written now.
  3. Close the window with its close button. OnExiting saves anything still pending.
  4. Read the file. Open a terminal and print the profile. The folder is the one in Figure 16-2. In PowerShell, run Get-Content "$env:LOCALAPPDATA\LastPerimeter\profile.json". In bash on Linux, run cat ~/.local/share/LastPerimeter/profile.json. In bash on macOS, run cat "$HOME/Library/Application Support/LastPerimeter/profile.json". If a command reports no such file, run find ~ -name profile.json -path "*LastPerimeter*" to find it. HighScore equals your last score. TotalRunsPlayed is 1, TotalDeaths is 3 and TotalCapturesCompleted is at least 1. This proves PRO-01.
  5. Start again. Run the game again and press Enter. The HUD shows HI: with the score you just printed, as in Figure 16-1.

TIP

To watch a corrupt file recover, close the game, open profile.json in a text editor, delete the last } and save. Run the game. It starts with HI:0, and the next save replaces the broken file with a valid one.

Finally, check that the smoke run leaves your real profile alone. Note the time of profile.json from step 4. In PowerShell, from the LastPerimeter folder, run dotnet run --project Platforms/DesktopVK -- --smoke-test-seconds 3 and then $LASTEXITCODE. In bash, run the same dotnet command and then echo $?. The exit code is 0. Print the real file again with the command from step 4. Its values and time have not changed. The smoke run wrote its own file under the system temp folder, in LastPerimeter-smoke/profile.json.

The next section is optional. It replaces your files with the chapter 16 snapshot.

If you got lost ​

This section is optional. Use it only when your project no longer builds or the tests no longer match this chapter. It overwrites your Source and Tests folders with the chapter 16 snapshot, so any change of your own in those folders is lost. <course-repo> is the folder where you cloned the course repository.

WARNING

These commands overwrite your own changes in Source and Tests. Copy your project folder elsewhere first if you want to keep it.

In PowerShell, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

powershell
$snapshot = "<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/16-Profiles-Settings-And-Saving"
Remove-Item -Recurse -Force Source, Tests
Copy-Item -Recurse "$snapshot/Source" Source
Copy-Item -Recurse "$snapshot/Tests" Tests

In bash, from the LastPerimeter folder, run the following. Replace <course-repo> with the real path first.

bash
snapshot="<course-repo>/DOCUMENTATION/learning_plan_2/snapshots/16-Profiles-Settings-And-Saving"
rm -rf Source Tests
cp -r "$snapshot/Source" Source
cp -r "$snapshot/Tests" Tests

Then run dotnet test from the LastPerimeter folder and check for Passed: 126.

Common mistakes ​

  • A NotImplementedException in the final test run. A stub remains in ProfileStorage.cs or ProfileTracker.cs. Search the file for throw new NotImplementedException(); and replace that method.
  • The build fails in LastPerimeterApp.cs with a missing CanSave. The scene manager step was skipped. Add CanSave to SceneManager.cs.
  • The build fails with too few arguments to GameServices. The constructor change is missing, or the host still passes the old arguments.
  • HI: stays at 0 after a run. Either RecordRunFinished is missing from the RunLost case, or CreateSimulation does not copy the stored HighScore into the session. The file on disk shows which.
  • The profile is never written. The host calls SaveIfDirty only when CanSave is true. If a scene other than GameplayScene returns false from AllowsSaving, the game saves only on exit.
  • A test leaves a folder in the temporary folder. The Dispose method is missing from the test class, or the class does not implement IDisposable.

Conclusion ​

In this chapter, you accomplished the following:

The tests now prove PRO-02 to PRO-08, SCO-07 and NFR-02, and the run of the game proves PRO-01. In the next chapter, Chapter 17: Menus and the Front End, you build the menus, the options screen and the tutorial, using the settings and the tracker you added here.

Test Your Knowledge ​

  1. What happens to the old profile if the game crashes halfway through Save?

    Answer

    Nothing happens to it. The write goes to a temporary file, and the swap only happens once the write has finished. The old file is intact until the move.

  2. Why does a failed save not retry every frame?

    Answer

    SaveIfDirty clears the dirty flag before it saves. The next real change sets it again, so a locked file costs one attempt per change and not sixty a second.

  3. Why does the profile update in GameplayScene.React and not inside the simulation?

    Answer

    The profile is persistence, not a rule of play. Keeping it out lets the simulation run in tests with no file system, and the scene is the one place that already decides what each event means to the player.

  4. What would go wrong if Load caught every exception with a bare catch?

    Answer

    A real bug, such as a null reference in your own code, would be hidden. The game would start with a blank profile and nothing would show the cause. Catching only file and format errors lets a bug still crash where you can see it.

Extensions ​

  • Add a test that saves a profile, deletes the real file, and checks that Load gives a fresh profile. Which test in this chapter already covers most of it?
  • Change SaveIfDirty so that it does not clear IsDirty when the save fails. Run the game with the profile file set to read-only and watch what happens. Why is this worse?