Skip to content

Save settings in your game

This page makes the game from Get the starter project remember where the player left the greeting. Pressing Space saves the point the greeting circles to a small file in the player’s own folder, and the next time the game starts, it starts there. It adds two files of your own, game\settings.h and game\settings.cpp, lists the new .cpp in game\CMakeLists.txt, and changes a few lines in HelloState. Then it opens the file, changes it by hand, breaks it on purpose to see the message, and deletes it to start again. It takes about 15 minutes.

Before you start:

  • Do Make a first change, so that you know the edit, build and run loop and have a copy of your game to go back to. Make a fresh copy now with that page’s step 1 line.

This page does not depend on the picture, animation or font pages, and works whether or not you have done them. Every command runs in the x64 Native Tools Command Prompt, in your project’s folder:

Terminal window
cd /d C:\dev\mygame
  1. Make the settings header. A header says what a .cpp file offers, so that other files can use it. First make the empty file, then open it:

    Terminal window
    if not exist game\settings.h type nul > game\settings.h
    notepad game\settings.h

    The first line makes an empty file and prints nothing; it leaves the file alone if it is already there. Notepad opens the empty file. Paste all of this into it, then save and close Notepad:

    game\settings.h
    #pragma once
    #include "engine/math/vector2f.h"
    #include <filesystem>
    // What the game keeps from one run to the next. It is written to
    // settings.json, in the folder settings_directory() names.
    struct Settings
    {
    // The point the greeting circles.
    labrador::Vector2F greeting_centre = { 0.0f, 0.0f };
    };
    // The folder the settings file goes in: %LOCALAPPDATA%\MyGame on Windows,
    // and /save in a browser, where it lasts until the page is reloaded.
    std::filesystem::path settings_directory();
    // Writes settings.json in directory, making the folder first if it is not
    // there. Throws if the file cannot be written.
    void write_settings(const std::filesystem::path& directory,
    const Settings& settings);
    // Reads settings.json from directory. Returns defaults when there is no
    // file, and throws, naming the file, when the file is there but wrong.
    Settings read_settings(const std::filesystem::path& directory,
    const Settings& defaults);

    Settings holds what the game saves, one position for now. The three functions below it find the folder, write the file and read it. The file goes straight in game, beside main.cpp, because it is not a screen of the game: so it is game\settings.h, and other files include it as "game/settings.h".

  2. Make the settings code. Make the second file and open it the same way:

    Terminal window
    if not exist game\settings.cpp type nul > game\settings.cpp
    notepad game\settings.cpp

    Paste all of this into it, then save and close Notepad:

    game\settings.cpp
    #include "game/settings.h"
    #include "engine/assets/json.h"
    #include "engine/render/text_encoding.h"
    #include <exception>
    #include <fstream>
    #include <memory>
    #include <stdexcept>
    #include <string>
    #if !defined(__EMSCRIPTEN__)
    #include <windows.h>
    #include <shlobj.h>
    #endif
    using namespace labrador;
    namespace
    {
    // The shape of the file this game writes. A later version of the game
    // that stores something else writes 2, and can still tell a 1 apart.
    constexpr int settings_version = 1;
    }
    std::filesystem::path settings_directory()
    {
    #if defined(__EMSCRIPTEN__)
    return "/save";
    #else
    wchar_t* raw = nullptr;
    if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_CREATE,
    nullptr, &raw)))
    {
    throw std::runtime_error("Cannot find this user's LocalAppData folder");
    }
    // Windows made the text, and it must be given back to Windows.
    struct FolderDeleter
    {
    void operator()(wchar_t* value) const
    {
    CoTaskMemFree(value);
    }
    };
    const std::unique_ptr<wchar_t, FolderDeleter> folder(raw);
    return std::filesystem::path(folder.get()) / L"MyGame";
    #endif
    }
    void write_settings(const std::filesystem::path& directory,
    const Settings& settings)
    {
    std::filesystem::create_directories(directory);
    std::ofstream output(directory / "settings.json",
    std::ios::binary | std::ios::trunc);
    output.exceptions(std::ios::failbit | std::ios::badbit);
    output << "{\n"
    << " \"version\": " << settings_version << ",\n"
    << " \"greeting_x\": " << settings.greeting_centre.x << ",\n"
    << " \"greeting_y\": " << settings.greeting_centre.y << "\n"
    << "}\n";
    output.close();
    }
    Settings read_settings(const std::filesystem::path& directory,
    const Settings& defaults)
    {
    const std::filesystem::path path = directory / "settings.json";
    if (!std::filesystem::exists(path))
    {
    return defaults;
    }
    const std::string name = narrow(path.wstring());
    try
    {
    const JsonDocument document = read_json_file(name.c_str());
    const JsonValue root = document.root();
    if (root.integer("version") != settings_version)
    {
    throw std::runtime_error("'" + name + "' has version " +
    std::to_string(root.integer("version")) +
    ", and this game reads version " +
    std::to_string(settings_version));
    }
    Settings settings;
    settings.greeting_centre = Vector2F(root.number("greeting_x"),
    root.number("greeting_y"));
    return settings;
    }
    catch (const std::exception& error)
    {
    throw std::runtime_error(std::string(error.what()) +
    ". Correct the file, or delete it to start from the defaults.");
    }
    }

    What each part does:

    • settings_directory asks Windows for the player’s LocalAppData folder, such as C:\Users\you\AppData\Local, and adds MyGame to it. A game must not save beside its .exe: an installed game can be in a folder nobody may write to. SHGetKnownFolderPath hands back text that Windows owns, and CoTaskMemFree gives it back; the small FolderDeleter does that whatever happens. Replace MyGame with your game’s name if you like, and then keep it: a different name is a different folder, and the old file is left behind. In a browser there is no such folder, and the lines under #if defined(__EMSCRIPTEN__) use /save instead; In the browser build says what that means.
    • write_settings makes the folder if it is not there, opens settings.json, and writes it a line at a time. output.exceptions(...) makes a failed write throw, rather than fail quietly, so the game can tell the player that the save did not happen.
    • read_settings returns the defaults it is given when there is no file: the first time the game runs, or after you delete the file. Otherwise it reads the file with the engine’s read_json_file, checks that version is 1, and reads the two numbers. Every one of those reads stops with a message that names the file and what is wrong with it, and the catch adds what to do about it. It never replaces a file it cannot read, because that file may be the only copy of what the player saved.

    The engine reads JSON but does not write it, so write_settings writes the text itself. That is fine for a few numbers. Settings and saves says more about the choices here.

  3. List settings.cpp in the build, twice. Every .cpp file in your game is listed by name in game\CMakeLists.txt, and a file that is not listed is not compiled. The game’s own files are listed twice: once for the browser build, and once for Windows. A file missing from one list breaks only that build, so add it to both now, even if you never build for the browser. Open the build file:

    Terminal window
    notepad game\CMakeLists.txt

    First, search with Ctrl+F for main_web.cpp. The first match is in the comment # The browser build: main_web.cpp in place of main.cpp; press Enter in the search box (or F3) to go to the next one. You are now in the browser’s list, near the top:

    add_executable(MyGame
    main_web.cpp
    states/confirm_state.cpp
    states/hello_state.cpp
    )

    Add a line after main_web.cpp, with the same spaces in front of it, so the list reads:

    add_executable(MyGame
    main_web.cpp
    settings.cpp
    states/confirm_state.cpp
    states/hello_state.cpp
    )

    Next, search for add_executable(MyGame WIN32. This is the Windows list, with the libraries the game links just below it:

    add_executable(MyGame WIN32
    main.cpp
    states/confirm_state.cpp
    states/hello_state.cpp
    dpi_aware.manifest
    )
    target_link_libraries(MyGame PRIVATE
    MyGameRules
    LabradorEngine
    labrador_settings
    )

    Add settings.cpp after main.cpp, and shell32 and ole32 after labrador_settings, so the lines read:

    add_executable(MyGame WIN32
    main.cpp
    settings.cpp
    states/confirm_state.cpp
    states/hello_state.cpp
    dpi_aware.manifest
    )
    target_link_libraries(MyGame PRIVATE
    MyGameRules
    LabradorEngine
    labrador_settings
    shell32
    ole32
    )

    shell32 and ole32 are the Windows libraries that SHGetKnownFolderPath and CoTaskMemFree come from. They go only in this Windows half: the browser has neither. The names settings.cpp are written from the game folder, because that is where this build file is. Save and close Notepad.

  4. Make room for a status line. Open the header of the state that runs the starter’s screen:

    Terminal window
    notepad game\states\hello_state.h

    Search for hint_ = nullptr; and add a line after it, so the two read:

    labrador::Label* hint_ = nullptr;
    labrador::Label* status_ = nullptr;

    status_ is a line of text that will say Saved., or why a save failed. If another page has already added a line after hint_, add this one after that. Save and close Notepad.

  5. Load the settings when the game starts. Open the state’s code:

    Terminal window
    notepad game\states\hello_state.cpp

    It needs three more #include lines. Search for engine/math/vector2f.h and add a line after it, so the two read:

    #include "engine/math/vector2f.h"
    #include "engine/render/text_encoding.h"

    If engine/render/text_encoding.h is there already, from Fonts and text in your game, leave it and do not add a second one. Then search for game/states/confirm_state.h and add a line above it, so the two read:

    #include "game/settings.h"
    #include "game/states/confirm_state.h"

    Then search for #include <cstddef> and add a line after it, so the two read:

    #include <cstddef>
    #include <exception>

    Now search for resolution.y * 0.5f);. These lines, at the start of init(), put the greeting in the middle of the window:

    samples/minimal/states/hello_state.cpp
    this->motion_.centre = Vector2F(resolution.x * 0.5f - 120.0f,
    resolution.y * 0.5f);

    Click at the end of the second line, after the ;, press Enter, and paste these lines:

    // Start where the player saved, or in the middle if nothing is saved.
    Settings defaults;
    defaults.greeting_centre = this->motion_.centre;
    const Settings settings = read_settings(settings_directory(), defaults);
    this->motion_.centre = settings.greeting_centre;

    The middle of the window becomes the default, and what read_settings returns replaces it: the saved point if there is a file, the middle if there is not. If the file is broken, read_settings throws, and the game stops at start-up with the message, as How errors show describes.

  6. Add the status line. In the same file, search for this->hint_ = this->scene_->add(. Click at the start of that line and paste these lines above it, with an empty line after them:

    this->status_ = this->scene_->add(std::make_unique<Label>(
    L"Space saves where the greeting is.", font_name,
    Vector2F(24.0f, resolution.y - 70.0f), resources,

    This is a Label like the hint, in the same grey, 30 pixels above it.

  7. Save when the player presses Space. In the same file, search for this->motion_ = step_motion(. These lines, in update(), move the greeting on each step:

    samples/minimal/states/hello_state.cpp
    this->motion_ = step_motion(this->motion_,
    stick_direction,
    keyboard_direction(keyboard), dt);

    Click at the start of the first of them and paste these lines above it, with an empty line after them:

    // Space saves the point the greeting circles, for the next start.
    if (keyboard.pressed(Key::space))
    {
    try
    {
    Settings settings;
    settings.greeting_centre = this->motion_.centre;
    write_settings(settings_directory(), settings);
    this->status_->set_text(L"Saved.");
    }
    catch (const std::exception& error)
    {
    this->status_->set_text(L"Could not save: " + widen(error.what()));
    }
    }

    keyboard.pressed(Key::space) is true on the one step on which Space goes down, so holding it saves once. try runs the save, and if anything in it throws, catch puts the reason on the status line instead of Saved., and the game goes on. widen turns the reason into the wide text a Label draws. Space is free in the starter: the arrows and W, A, S and D move the greeting, and Escape asks to quit. A function key such as F5, the usual quick-save key, would work on Windows, but a browser keeps the function keys for itself, and F5 reloads the page. Save and close Notepad.

  8. Build, test and run. Quit the game if it is open, then run the line from Make a first change’s step 5:

    Terminal window
    cmake --build --preset x64-debug && ctest --preset x64-debug && out\build\x64-debug\game\MyGame.exe

    The build first runs CMake again, because game\CMakeLists.txt changed. That prints [0/1] Re-running CMake... and about 30 lines from vcpkg and CMake, including a list of packages and package-lookup lines; they are expected, not errors. Then it compiles settings.cpp for the first time, and the two files that include hello_state.h. On a fast desktop the whole line took 5 seconds before the game opened. It ends like this:

    Output
    -- Build files have been written to: C:/dev/mygame/out/build/x64-debug
    [1/7] Running utility command for game_content
    [2/7] Checking that no engine file includes a game header
    [3/7] Building CXX object game\CMakeFiles\MyGame.dir\main.cpp.obj
    [4/7] Building CXX object game\CMakeFiles\MyGame.dir\states\hello_state.cpp.obj
    [5/7] Building CXX object game\CMakeFiles\MyGame.dir\settings.cpp.obj
    [6/7] Linking CXX executable game\MyGame.exe
    Test project C:/dev/mygame/out/build/x64-debug
    Start 1: MyGameTests
    1/2 Test #1: MyGameTests ...................... Passed 0.01 sec
    Start 2: MyGameSmokeTests
    2/2 Test #2: MyGameSmokeTests ................. Passed 0.68 sec
    100% tests passed, 0 tests failed out of 2

    Then the game opens, with the greeting in the middle, because nothing is saved yet. Above the controls hint, a new grey line says Space saves where the greeting is.

  9. Save, and start again. Move the greeting with the arrow keys or WASD, up and to the left for example, and press Space. The grey line changes to Saved. Quit the game: Escape, then Enter. Start it again:

    Terminal window
    out\build\x64-debug\game\MyGame.exe

    The greeting starts where you left it, still circling, and the grey line says Space saves where the greeting is. again. Quit it before you go on.

The game wrote settings.json in your LocalAppData folder. %LOCALAPPDATA% is that folder’s name in the prompt, so type can show the file without your having to know where it is:

Terminal window
type "%LOCALAPPDATA%\MyGame\settings.json"
Output
{
"version": 1,
"greeting_x": 313.335,
"greeting_y": 160.001
}

Your numbers depend on where you left the greeting. They are pixels from the window’s left edge and from its top: the window is 1280 wide and 720 high. The greeting starts at 520, 360: halfway down, and 120 pixels left of halfway across (640), so that the text, which starts at the point and runs to the right, looks centred. The point is the one the greeting circles, not the corner of its text. To see the whole path, run echo %LOCALAPPDATA%\MyGame; it prints a path such as C:\Users\you\AppData\Local\MyGame, with your Windows user name.

Open the file in Notepad:

Terminal window
notepad "%LOCALAPPDATA%\MyGame\settings.json"

Change the two numbers, keeping the comma after the first and the quotation marks round the names, so the file reads:

%LOCALAPPDATA%\MyGame\settings.json
{
"version": 1,
"greeting_x": 900,
"greeting_y": 500
}

Save and close Notepad, then start the game with the line from step 9. It starts with the greeting in the lower right of the window, without a rebuild: the game reads the file each time it starts. A whole number such as 900 is read the same as 900.0.

Delete the file:

Terminal window
del "%LOCALAPPDATA%\MyGame\settings.json"

It prints nothing. The next time the game starts, there is no file, so read_settings returns the defaults, and the greeting starts in the middle. If del prints Could Not Find C:\Users\...\MyGame\settings.json, there was no file to delete: nothing had been saved, or it was deleted already. After the delete, type on the file prints The system cannot find the file specified.

A mistake in this page’s work shows in one of four places:

  • The build stops with an error line: a slip in the C++ code or a file missing from a list in game\CMakeLists.txt. Read a build error shows how to find the line that matters, and the link errors are below.

  • The start-up test fails because settings.json is there but wrong. The game reads the file in init(), and so does the start-up test, which runs the game hidden on your computer with your file. The ctest output shows ***Failed for MyGameSmokeTests and, under it, a line starting startup failure: that names the file and says what is wrong:

    Output
    2/2 Test #2: MyGameSmokeTests .................***Failed 0.24 sec
    startup failure: read_json_file - 'C:\Users\...\MyGame\settings.json' is not valid JSON: Missing a comma or '}' after an object member. (offset 46). Correct the file, or delete it to start from the defaults.
    50% tests passed, 1 tests failed out of 2

    Started on its own, the game shows the message, without startup failure: in front, in a box titled Sample - startup failure, and closes when you click OK. Correct the file, or delete it as in Start again from the defaults.

  • The status line says Could not save: and a reason, when you press Space and the file cannot be written. The game goes on. When the file could not be opened, as in the message below, the old file, if there is one, is as it was.

  • The browser build stops with wasm-ld: error, when settings.cpp is in the Windows list but not the browser’s. The Windows build works, so this shows only when you build for the browser.

Each message is below.

The greeting starts in the middle after you saved. The game read no file. Check with the type line in Look at the file. If the file is there, the build may not have the code that reads it: run the build line from step 8 and read its last lines for an error.

Space does nothing. The game window must have the keyboard: click it first. If it still does nothing, check the lines from step 7 against the page, and that the build worked.

Leaving out shell32 and ole32. With the starter, the build still works without the two library names from step 3, because CMake passes both to Visual Studio’s linker for every program anyway. Keep them: they say what settings.cpp needs, and do not depend on that default.

With settings.cpp in both lists, the browser build compiles and runs the same code, and Space saves there too. A page has no LocalAppData folder: settings_directory() returns /save, a folder in the page’s own memory, and the file written there is read back if the game reads it again while the page is open. Reloading the page or closing it loses it, and the game starts in the middle again. shell32 and ole32 are only in the Windows half of game\CMakeLists.txt, so the browser build does not look for them.

To keep the file after a reload, the page must copy /save to the browser’s own storage and back. Settings and saves shows how, with a small JavaScript file and two link options. Those restore /save when the page starts; a file saved with Space still needs copying back after each save, which is the Module.flushSave() call in Finish the browser sync before saying saved. Without it, the file is gone after a reload, as before.

To save something else, add a field to Settings in settings.h, a line that writes it in write_settings, and a line that reads it in read_settings. A file saved before the new field existed does not have it, and stops the game with the document has no and its name; delete the file, or read the field only when root.has("its_name") is true, and keep the default otherwise.

On 2026-10-30, in a starter project made from a starter ZIP of this tree at C:\dev\h7\mygame, with Visual Studio 2026’s compiler 19.51, every step above was made exactly as worded, by an agent editing the files rather than in Notepad, and ran as shown, with C:\dev\h7\mygame in the quoted output changed to C:\dev\mygame and the Windows user name in the file’s path changed to .... Window captures showed the new grey line, Saved. after the arrows and Space, the greeting starting where it was saved after a restart, and in the lower right after the file was changed by hand to 900, 500. The type, del and attrib lines printed what is quoted. Each message under If something fails was made on purpose: settings.cpp left out of each list, a missing comma, version 2, a missing greeting_y, a quoted number, and a read-only file. The Sample - startup failure box was captured with the quoted number in the file: it showed the message without startup failure: in front, and an OK button. The build without shell32 and ole32 linked and passed both tests, and the build folder’s CMakeCache.txt showed CMake’s default list naming shell32.lib and ole32.lib. The wasm-debug build compiled the page under clang and passed its test, and the page runner loaded it in headless Chrome, pressed Space, then Escape and Enter, and reached Module.onQuit with nothing in the console; a temporary line printed after the save reported /save/settings.json. The save check’s whole settings.cpp in place of the one above stopped the browser build with duplicate symbol: __original_main, then main and __main_void. A volume field added as the last section describes, read only when root.has("volume"), built cleanly and read a file saved without it. Keeping the browser file after a reload was not tried on this page. On 2026-11-13 it was, in headless Chrome, with the link options from Settings and saves added: the file saved with Space was gone after a reload until Module.flushSave() was called after the save, and then the game started where it was saved. That page’s What was checked has the run.

A second agent then followed the page as worded in a fresh starter at C:\dev\h7v\mygame, and its builds, tests, window captures, commands and every message above matched. It found that the first main_web.cpp in step 3 is in a comment, that the middle of the window was given as 520 where half of 1280 is 640, that the link error’s two long lines had been dropped without saying so, that a failed save keeps the old file only when the file could not be opened, that the start-up box leaves out startup failure:, and that the duplicate-main error first names __original_main; the page was corrected from that run’s captured output. It did not check the root.has note.

Development documentation (unreleased). Built from Labrador aceb130 of 2026-11-20.

All documentation versions