← All Workshops

MudEngine Part 9: The Twin Guardians

Step 5 / 12

Persist quest state

The quest has exactly one live bit worth persisting: completed. It belongs in Players.toml (live state) next to the players and the ground — never in Game.toml.

Three additions, all inside persistence.rs, keeping the Part 8 shape:

  1. load_quest — read the static [quest] config from Game.toml (the vault room already loads through load_world)
  2. load_players — LiveState also returns quest_completed from Players.toml
  3. snapshot — writes quest_completed to Players.toml

Game.toml stays read-only, exactly as in Part 7 and 8 — the autosave task still owns every disk write.

mud-engine/src/game/persistence.rs
#[cfg(feature = "server")]
/// Read the static `[quest]` section from Game.toml, if present.
pub fn load_quest(path: &str) -> Option<TomlQuest> {
    let toml_game: TomlQuestConfig = toml::from_str(
        &std::fs::read_to_string(path)
            .unwrap_or_else(|e| panic!("Failed to read {}: {}", path, e)),
    )
    .unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));
    toml_game.quest
}

#[cfg(feature = "server")]
#[derive(Deserialize)]
struct TomlQuestConfig {
    #[serde(default)]
    quest: Option<TomlQuest>,
}
mud-engine/src/game/persistence.rs
#[derive(Serialize, Deserialize)]
struct TomlPlayers {
    #[serde(default)]
    players: Vec<PlayerInfo>,
    #[serde(default)]
    room_items: Vec<TomlRoomItems>,
    /// Live quest bit: whether the quest is complete.
    #[serde(default)]
    quest_completed: Option<bool>,
}

#[cfg(feature = "server")]
/// What load_players returns: the live players, ground overrides, and quest flag.
pub struct LiveState {
    pub players: HashMap<String, PlayerInfo>,
    /// rooms whose ground has diverged from the Game.toml seed
    pub ground: HashMap<usize, Vec<String>>,
    /// persisted quest completion flag (None when never set)
    pub quest_completed: Option<bool>,
}

#[cfg(feature = "server")]
pub fn load_players(path: &str) -> LiveState {
    let Ok(content) = std::fs::read_to_string(path) else {
        return LiveState {
            players: HashMap::new(),
            ground: HashMap::new(),
            quest_completed: None,
        };
    };
    let toml_players: TomlPlayers =
        toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));

    let players = toml_players
        .players
        .into_iter()
        .map(|p| (p.id.clone(), p))
        .collect();

    let ground = toml_players
        .room_items
        .into_iter()
        .map(|ri| (ri.room, ri.items))
        .collect();

    LiveState {
        players,
        ground,
        quest_completed: toml_players.quest_completed,
    }
}
mud-engine/src/game/persistence.rs
#[cfg(feature = "server")]
/// Serialize the live state into the TOML that goes into Players.toml.
/// Fast (a few strings), so it is safe to run while holding the lock.
/// The disk write itself happens separately, in `write_players`.
pub fn snapshot(state: &GameState) -> String {
    let toml_players = TomlPlayers {
        players: state.players.values().cloned().collect(),
        room_items: state
            .ground
            .iter()
            .map(|(room, items)| TomlRoomItems {
                room: *room,
                items: items.clone(),
            })
            .collect(),
        quest_completed: state.quest.as_ref().map(|q| q.completed),
    };
    toml::to_string_pretty(&toml_players).unwrap()
}
🎯 Static config, live flag

The quest is split down the middle by the Part 7 file convention:

  • Game.toml — the [quest] table is static config. load_quest reads it once at startup; the file is never written at runtime. Same for the vault room (id 9): plain static data with exits = [].
  • Players.toml — the only live quest bit is quest_completed, written by the autosave task exactly like players and ground.

Notice what is not persisted: previously_active and the dynamic portal exits. They are session state — after a restart the portal simply re-opens the next time two players stand on the pedestals, and update_quest rebuilds the exits in memory. Same pattern as the ground seed: static file, live memory, periodic flush of what matters.

Step 5 / 12