Skip to main content

Module storage

Module storage 

Source
Expand description

Simple saving: high scores, settings, progress. Available as ctx.storage.

Values are stored as text in a small key = value file that is loaded when the game starts and written when it quits (or when you call Storage::save).

let best: u32 = ctx.storage.get_or("highscore", 0);
if score > best {
    ctx.storage.set("highscore", score);
    ctx.speak("New high score!");
}
let volume: f32 = ctx.storage.get_or("volume", 0.8);

The file is <game title>.save in the working directory (in a macOS app bundle: ~/Library/Application Support/<game title>/) unless set with Engine::save_file. Anything that implements Display and FromStr can be stored: numbers, bool, String, …

§Encryption (optional)

By default the file is plain text, so players can read and edit it. With Engine::encrypt_save (or Storage::open_encrypted) the file is encrypted with XChaCha20-Poly1305, using a key made from a secret word you choose:

fn main() -> audio_code::Result<()> {
    Engine::new("My game").encrypt_save("my secret word").run(Game)
}
  • Nothing else changes: ctx.storage.get / set work as before.
  • The file cannot be read, and any change to it is detected. A file that cannot be decrypted (wrong secret, edited or damaged) is not overwritten: it is renamed to <file>.broken, the game starts with empty storage, and Storage::load_error says why.
  • An existing plain text save is read once and written encrypted on the next save, so turning encryption on keeps the players’ progress.
  • The secret is compiled into your game, so a determined player can dig it out of the executable. Encryption stops casual cheating and accidental edits; it is not a safe place for real secrets such as passwords.

Structs§

Storage
Key-value storage that survives restarts, optionally encrypted.