Saving and restoring player preferences is an essential feature for any game. Here's how to implement a robust system for handling fullscreen preferences:
Here’s a basic framework that we can use to save and load display preferences:
#include <SDL.h>
#include <fstream>
#include <iostream>
struct DisplayPreferences {
enum class Mode {
Windowed,
DesktopFullscreen,
ExclusiveFullscreen
};
Mode FullscreenMode{Mode::Windowed};
int WindowWidth{1920};
int WindowHeight{1080};
int DisplayIndex{0};
};
void SavePreferences(
const DisplayPreferences& Prefs) {
std::ofstream File{
"display_prefs.dat", std::ios::binary};
File.write(
reinterpret_cast<const char*>(&Prefs),
sizeof(DisplayPreferences));
}
DisplayPreferences LoadPreferences() {
DisplayPreferences Prefs;
std::ifstream File{
"display_prefs.dat", std::ios::binary};
if (File) {
File.read(reinterpret_cast<char*>(&Prefs),
sizeof(DisplayPreferences));
}
return Prefs;
}
void ApplyPreferences(
SDL_Window* Window,
const DisplayPreferences& Prefs
) {
// First set window size
SDL_SetWindowSize(
Window,
Prefs.WindowWidth,
Prefs.WindowHeight);
// Then apply fullscreen mode
switch (Prefs.FullscreenMode) {
case DisplayPreferences::Mode::Windowed:
SDL_SetWindowFullscreen(Window, 0);
break;
case
DisplayPreferences::Mode::DesktopFullscreen:
SDL_SetWindowFullscreen(
Window, SDL_WINDOW_FULLSCREEN_DESKTOP);
break;
case
DisplayPreferences::Mode::ExclusiveFullscreen:
SDL_SetWindowFullscreen(
Window, SDL_WINDOW_FULLSCREEN);
break;
}
}
For a more maintainable solution, consider using JSON to store preferences:
#include <SDL.h>
#include <fstream>
#include <nlohmann/json.hpp>
void SavePreferencesJson(
const DisplayPreferences& Prefs
) {
nlohmann::json Json;
Json["fullscreen_mode"] =
static_cast<int>(Prefs.FullscreenMode);
Json["window_width"] =
Prefs.WindowWidth;
Json["window_height"] =
Prefs.WindowHeight;
Json["display_index"] =
Prefs.DisplayIndex;
std::ofstream File{"display_prefs.json"};
// Pretty print with 2 space indent
File << Json.dump(2);
}
The JSON approach makes the preferences file human-readable and easier to modify or debug. However, you'll need to include a JSON library in your project. We cover the popular nlohmann::json library here:
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create and manage fullscreen windows in SDL, including desktop and exclusive fullscreen modes.