Table of Contents

Settings Management

The Popcorning Guinea Pig engine provides a robust settings management system through the ISettingsService that handles game configuration, user preferences, and persistent storage.

Overview

The settings system allows you to:

  • Store and retrieve configuration values
  • Persist settings across game sessions
  • Handle different data types (strings, numbers, booleans, objects)
  • Provide default values for missing settings
  • Validate setting values

ISettingsService Interface

public interface ISettingsService
{
    T GetSetting<T>(string key, T defaultValue = default);
    void SetSetting<T>(string key, T value);
    bool HasSetting(string key);
    void RemoveSetting(string key);
    void SaveSettings();
    void LoadSettings();
    void ResetToDefaults();
}

Getting the Settings Service

Access the settings system through dependency injection:

public class MyGame : Game
{
    private readonly ISettingsService _settings;
    
    public MyGame()
    {
        _settings = GetService<ISettingsService>();
    }
}

Basic Usage

Storing Settings

// Store different types of settings
_settings.SetSetting("PlayerName", "John Doe");
_settings.SetSetting("MasterVolume", 0.8f);
_settings.SetSetting("FullscreenMode", true);
_settings.SetSetting("LastPlayedLevel", 5);

// Save settings to disk
_settings.SaveSettings();

Retrieving Settings

// Get settings with default values
string playerName = _settings.GetSetting("PlayerName", "Unknown Player");
float volume = _settings.GetSetting("MasterVolume", 1.0f);
bool isFullscreen = _settings.GetSetting("FullscreenMode", false);
int level = _settings.GetSetting("LastPlayedLevel", 1);

Checking for Settings

// Check if a setting exists
if (_settings.HasSetting("PlayerName"))
{
    var name = _settings.GetSetting<string>("PlayerName");
    // Use the setting
}

// Remove a setting
_settings.RemoveSetting("OldSetting");

Settings Categories

Organize settings using a naming convention with categories:

// Audio settings
_settings.SetSetting("Audio.MasterVolume", 0.8f);
_settings.SetSetting("Audio.MusicVolume", 0.7f);
_settings.SetSetting("Audio.SfxVolume", 0.9f);
_settings.SetSetting("Audio.MusicEnabled", true);

// Graphics settings
_settings.SetSetting("Graphics.Resolution", "1920x1080");
_settings.SetSetting("Graphics.Fullscreen", true);
_settings.SetSetting("Graphics.VSync", true);
_settings.SetSetting("Graphics.AntiAliasing", 4);

// Gameplay settings
_settings.SetSetting("Gameplay.Difficulty", "Normal");
_settings.SetSetting("Gameplay.AutoSave", true);
_settings.SetSetting("Gameplay.ShowTutorials", true);

Complex Settings with Objects

Store complex objects as settings:

// Define a settings class
public class GraphicsSettings
{
    public Resolution Resolution { get; set; } = new Resolution(1920, 1080);
    public bool Fullscreen { get; set; } = true;
    public bool VSync { get; set; } = true;
    public int AntiAliasing { get; set; } = 4;
    public float Brightness { get; set; } = 1.0f;
}

// Store and retrieve complex objects
var graphicsSettings = new GraphicsSettings();
_settings.SetSetting("GraphicsConfig", graphicsSettings);

var savedSettings = _settings.GetSetting<GraphicsSettings>("GraphicsConfig");

Settings Management Class

Create a dedicated settings manager for better organization:

public class GameSettingsManager
{
    private readonly ISettingsService _settings;
    
    public GameSettingsManager(ISettingsService settings)
    {
        _settings = settings;
        LoadDefaults();
    }
    
    // Audio Properties
    public float MasterVolume
    {
        get => _settings.GetSetting("Audio.MasterVolume", 1.0f);
        set => _settings.SetSetting("Audio.MasterVolume", value);
    }
    
    public float MusicVolume
    {
        get => _settings.GetSetting("Audio.MusicVolume", 0.8f);
        set => _settings.SetSetting("Audio.MusicVolume", value);
    }
    
    // Graphics Properties
    public bool Fullscreen
    {
        get => _settings.GetSetting("Graphics.Fullscreen", false);
        set => _settings.SetSetting("Graphics.Fullscreen", value);
    }
    
    public Resolution Resolution
    {
        get => _settings.GetSetting("Graphics.Resolution", new Resolution(1280, 720));
        set => _settings.SetSetting("Graphics.Resolution", value);
    }
    
    // Methods
    public void ApplySettings()
    {
        // Apply audio settings
        var soundPlayer = GetService<ISoundPlayer>();
        soundPlayer.SetMusicVolume(MusicVolume);
        
        // Apply graphics settings
        SetFullscreen(Fullscreen);
        SetResolution(Resolution);
        
        // Save changes
        Save();
    }
    
    public void Save()
    {
        _settings.SaveSettings();
    }
    
    public void ResetToDefaults()
    {
        _settings.ResetToDefaults();
        LoadDefaults();
    }
    
    private void LoadDefaults()
    {
        // Ensure all settings have proper defaults
        _ = MasterVolume; // Triggers default value creation
        _ = MusicVolume;
        _ = Fullscreen;
        _ = Resolution;
    }
}

Integration with UI

Connect settings to UI elements for user configuration:

public class SettingsScene : Scene
{
    private readonly GameSettingsManager _gameSettings;
    private Slider _volumeSlider;
    private Toggle _fullscreenToggle;
    private Dropdown _resolutionDropdown;
    
    public SettingsScene(GameSettingsManager gameSettings)
    {
        _gameSettings = gameSettings;
        CreateUI();
    }
    
    private void CreateUI()
    {
        // Volume slider
        _volumeSlider = new Slider
        {
            Value = _gameSettings.MasterVolume,
            OnValueChanged = (value) => _gameSettings.MasterVolume = value
        };
        
        // Fullscreen toggle
        _fullscreenToggle = new Toggle
        {
            IsChecked = _gameSettings.Fullscreen,
            OnToggled = (isChecked) => _gameSettings.Fullscreen = isChecked
        };
        
        // Resolution dropdown
        _resolutionDropdown = new Dropdown
        {
            SelectedIndex = GetResolutionIndex(_gameSettings.Resolution),
            OnSelectionChanged = (index) => 
            {
                _gameSettings.Resolution = GetResolutionByIndex(index);
            }
        };
        
        // Apply button
        var applyButton = new Button
        {
            Text = "Apply Settings",
            OnClick = () => _gameSettings.ApplySettings()
        };
        
        AddElement(_volumeSlider);
        AddElement(_fullscreenToggle);
        AddElement(_resolutionDropdown);
        AddElement(applyButton);
    }
}

File Storage

Settings are stored in a platform-specific location:

  • Windows: %APPDATA%/YourGame/settings.json
  • Linux: ~/.config/YourGame/settings.json
  • macOS: ~/Library/Application Support/YourGame/settings.json

Custom Storage Location

Override the default storage location:

public class CustomSettingsService : ISettingsService
{
    private readonly string _settingsPath;
    
    public CustomSettingsService(string customPath)
    {
        _settingsPath = customPath;
    }
    
    // Implementation...
}

Validation and Constraints

Add validation to ensure setting values are within acceptable ranges:

public class ValidatedSettingsManager : GameSettingsManager
{
    public override float MasterVolume
    {
        get => base.MasterVolume;
        set => base.MasterVolume = Math.Clamp(value, 0.0f, 1.0f);
    }
    
    public override Resolution Resolution
    {
        get => base.Resolution;
        set
        {
            // Only allow supported resolutions
            var supportedResolutions = GetSupportedResolutions();
            if (supportedResolutions.Contains(value))
                base.Resolution = value;
        }
    }
}

Best Practices

Organization

  1. Use consistent naming: Follow a hierarchical naming scheme (Category.Setting)
  2. Group related settings: Keep similar settings together
  3. Provide meaningful defaults: Always specify reasonable default values

Performance

  1. Cache frequently accessed settings: Store commonly used values in memory
  2. Batch saves: Don't save after every setting change, batch them together
  3. Load on startup: Initialize settings early in the application lifecycle

User Experience

  1. Immediate feedback: Show setting changes immediately in the UI
  2. Confirmation dialogs: Ask before applying major changes (like resolution)
  3. Reset options: Provide a way to restore default settings

Example: Complete Settings Implementation

public class MyGame : Game
{
    private readonly GameSettingsManager _settings;
    
    public MyGame()
    {
        var settingsService = GetService<ISettingsService>();
        _settings = new GameSettingsManager(settingsService);
        
        // Load settings and apply them
        InitializeWithSettings();
    }
    
    private void InitializeWithSettings()
    {
        // Apply audio settings
        var soundPlayer = GetService<ISoundPlayer>();
        soundPlayer.SetMusicVolume(_settings.MusicVolume);
        soundPlayer.SetSoundVolume(_settings.SfxVolume);
        
        // Apply graphics settings
        if (_settings.Fullscreen)
            ToggleFullscreen();
            
        SetWindowSize(_settings.Resolution.Width, _settings.Resolution.Height);
    }
    
    protected override void OnClosing()
    {
        // Save settings before closing
        _settings.Save();
        base.OnClosing();
    }
}

The settings system provides a flexible and powerful way to manage game configuration and user preferences in your Popcorning Guinea Pig games.