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:
cd /d C:\dev\mygame-
Make the settings header. A header says what a
.cppfile 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.hnotepad game\settings.hThe 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.};// 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);Settingsholds 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 ingame, besidemain.cpp, because it is not a screen of the game: so it isgame\settings.h, and other files include it as"game/settings.h". -
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.cppnotepad game\settings.cppPaste 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>#endifusing 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";#elsewchar_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;}try{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;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_directoryasks Windows for the player’s LocalAppData folder, such asC:\Users\you\AppData\Local, and addsMyGameto it. A game must not save beside its.exe: an installed game can be in a folder nobody may write to.SHGetKnownFolderPathhands back text that Windows owns, andCoTaskMemFreegives it back; the smallFolderDeleterdoes that whatever happens. ReplaceMyGamewith 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/saveinstead; In the browser build says what that means.write_settingsmakes the folder if it is not there, openssettings.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_settingsreturns 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’sread_json_file, checks thatversionis1, 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 thecatchadds 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_settingswrites the text itself. That is fine for a few numbers. Settings and saves says more about the choices here. -
List settings.cpp in the build, twice. Every
.cppfile in your game is listed by name ingame\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.txtFirst, 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(MyGamemain_web.cppstates/confirm_state.cppstates/hello_state.cpp)Add a line after
main_web.cpp, with the same spaces in front of it, so the list reads:add_executable(MyGamemain_web.cppsettings.cppstates/confirm_state.cppstates/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 WIN32main.cppstates/confirm_state.cppstates/hello_state.cppdpi_aware.manifest)target_link_libraries(MyGame PRIVATEMyGameRulesLabradorEnginelabrador_settings)Add
settings.cppaftermain.cpp, andshell32andole32afterlabrador_settings, so the lines read:add_executable(MyGame WIN32main.cppsettings.cppstates/confirm_state.cppstates/hello_state.cppdpi_aware.manifest)target_link_libraries(MyGame PRIVATEMyGameRulesLabradorEnginelabrador_settingsshell32ole32)shell32andole32are the Windows libraries thatSHGetKnownFolderPathandCoTaskMemFreecome from. They go only in this Windows half: the browser has neither. The namessettings.cppare written from thegamefolder, because that is where this build file is. Save and close Notepad. -
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.hSearch for
hint_ = nullptr;and add a line after it, so the two read:labrador::Label* status_ = nullptr;status_is a line of text that will saySaved., or why a save failed. If another page has already added a line afterhint_, add this one after that. Save and close Notepad. -
Load the settings when the game starts. Open the state’s code:
Terminal window notepad game\states\hello_state.cppIt needs three more
#includelines. Search forengine/math/vector2f.hand 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.his there already, from Fonts and text in your game, leave it and do not add a second one. Then search forgame/states/confirm_state.hand 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 ofinit(), put the greeting in the middle of the window:samples/minimal/states/hello_state.cpp resolution.y * 0.5f);samples/minimal/states/hello_state.cpp, lines 77–78 at
0f4f503Click 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_settingsreturns replaces it: the saved point if there is a file, the middle if there is not. If the file is broken,read_settingsthrows, and the game stops at start-up with the message, as How errors show describes. -
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:L"Space saves where the greeting is.", font_name,This is a
Labellike the hint, in the same grey, 30 pixels above it. -
Save when the player presses Space. In the same file, search for
this->motion_ = step_motion(. These lines, inupdate(), move the greeting on each step:samples/minimal/states/hello_state.cpp this->motion_ = step_motion(this->motion_,stick_direction,keyboard_direction(keyboard), dt);samples/minimal/states/hello_state.cpp, lines 155–157 at
0f4f503Click 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.{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){}}keyboard.pressed(Key::space)is true on the one step on which Space goes down, so holding it saves once.tryruns the save, and if anything in it throws,catchputs the reason on the status line instead ofSaved., and the game goes on.widenturns the reason into the wide text aLabeldraws. 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. -
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.exeThe build first runs CMake again, because
game\CMakeLists.txtchanged. That prints[0/1] Re-running CMake...and about 30 lines from vcpkg and CMake, including a list of packages and lines such asfind_package(doctest CONFIG REQUIRED); they are expected, not errors. Then it compilessettings.cppfor the first time, and the two files that includehello_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.exeTest project C:/dev/mygame/out/build/x64-debugStart 1: MyGameTests1/2 Test #1: MyGameTests ...................... Passed 0.01 secStart 2: MyGameSmokeTests2/2 Test #2: MyGameSmokeTests ................. Passed 0.68 sec100% tests passed, 0 tests failed out of 2Then 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. -
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.exeThe 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.
Look at the file
Section titled “Look at the file”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:
type "%LOCALAPPDATA%\MyGame\settings.json"{ "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.
Change it by hand
Section titled “Change it by hand”Open the file in Notepad:
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:
{ "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.
Start again from the defaults
Section titled “Start again from the defaults”Delete the file:
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.
How errors show
Section titled “How errors show”A mistake in this page’s work shows in one of four places:
-
The build stops with an
errorline: a slip in the C++ code or a file missing from a list ingame\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.jsonis there but wrong. The game reads the file ininit(), and so does the start-up test, which runs the game hidden on your computer with your file. Thectestoutput shows***FailedforMyGameSmokeTestsand, under it, a line startingstartup failure:that names the file and says what is wrong:Output 2/2 Test #2: MyGameSmokeTests .................***Failed 0.24 secstartup 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 2Started on its own, the game shows the message, without
startup failure:in front, in a box titledSample - 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, whensettings.cppis 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.
If something fails
Section titled “If something fails”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.
In the browser build
Section titled “In the browser build”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.
Where to go next
Section titled “Where to go next”- Settings and saves applies settings such as full screen and volume to the running game, and keeps browser saves after a reload.
- Read a build error has more on the messages a build gives.
- Build for the browser builds the same game as a web page.
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.
What was checked
Section titled “What was checked”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.
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.
Documentation for Labrador v0.3.0. Built from Labrador 0f4f503 of 2026-11-03.