← All Workshops

MudEngine Part 9: The Twin Guardians

Step 7 / 12

Update the WebSocket Endpoint

Quest awareness touches the server/ modules you split out in Part 8. Four files change:

  1. server/mod.rs — declare mod quest;, extend the imports with the quest wire types, include quest: Option<QuestInfo> in the initial State message, and make the disconnect cleanup quest-aware
  2. server/move_handler.rs — map down/up too, allow the direct vault descent from Town Square while the gate is open, call update_quest() after moving, then check_quest_completion()
  3. server/take_handler.rs — call check_quest_completion() after a successful take
  4. server/drop_handler.rs — call check_quest_completion() after a successful drop

QuestEvent and QuestCompleted travel exactly like every other ServerMessage — through the same broadcast channel to every client.

First, in server/mod.rs, extend the imports so the handler sees the quest wire types, and declare the new quest module:

use super::messages::{ClientMessage, PlayerInfo, QuestGuardianInfo, QuestInfo, ServerMessage};

// ── Action handlers — one file per action ──
#[cfg(feature = "server")]
mod quest;

The State message now carries quest data

mud-engine/src/game/server/mod.rs
    // 4. Build the initial state snapshot for this new player
    let initial_state = {
        let state = GAME_STATE.lock().unwrap();
        ServerMessage::State {
            players: state.players.values().cloned().collect(),
            your_id: id.clone(),
            rooms: room_infos,
            quest: state.quest.as_ref().map(|q| QuestInfo {
                name: q.config.name.clone(),
                active: q.previously_active && !q.completed,
                completed: q.completed,
                guardians: q
                    .config
                    .guardians
                    .iter()
                    .map(|g| QuestGuardianInfo {
                        name: g.name.clone(),
                        room_id: g.room_id,
                        label: g.label.clone(),
                        // Which pedestals are occupied right now?
                        active: state.players.values().any(|p| p.room == g.room_id),
                    })
                    .collect(),
            }),
        }
    };
mud-engine/src/game/server/move_handler.rs
use super::quest;
use super::{BROADCAST, GAME_STATE};
use crate::game::messages::{PlayerInfo, ServerMessage};
use crate::game::persistence;

/// Handle a player move request. Quest-aware: maps `down`/`up`, allows the
/// direct vault descent from Town Square while the gate is open, and
/// re-evaluates the quest after the move.
pub fn run(player_id: String, player_name: String, direction: String) {
    let dir = match direction.as_str() {
        "n" => "north", "s" => "south",
        "e" => "east", "w" => "west",
        "down" | "d" => "down",
        "up" | "u" => "up",
        d => d,
    };

    let (new_room, quest_event, items) = {
        let mut state = GAME_STATE.lock().unwrap();

        let current = state.players.get(&player_id).unwrap().room;

        // Normal movement first — the vault has no exits, so can_move can
        // never lead there.
        let mut next = persistence::can_move(&state, current, dir);

        // Direct vault descent while the gate is open.
        if next.is_none() && dir == "down" && current == 4 {
            let q_active = state
                .quest
                .as_ref()
                .map(|q| q.previously_active)
                .unwrap_or(false);
            if q_active {
                next = Some(9);
            }
        }

        // Apply the move, then re-evaluate the quest gate.
        let quest_event = match next {
            Some(room) => {
                state.players.get_mut(&player_id).unwrap().room = room;
                quest::update_quest(&mut state)
            }
            None => None,
        };

        let items = state
            .players
            .get(&player_id)
            .map(|p| p.items.clone())
            .unwrap_or_default();

        (next, quest_event, items)
    };

    if let Some(room) = new_room {
        // Real inventory, so the roster stays accurate
        let _ = BROADCAST.send(ServerMessage::PlayerMoved(PlayerInfo {
            id: player_id.clone(),
            name: player_name.clone(),
            room,
            items,
        }));

        if let Some((active, message)) = quest_event {
            let _ = BROADCAST.send(ServerMessage::QuestEvent { active, message });
        }

        // Moving may have carried the Star Fragment home
        if let Some(message) = quest::check_quest_completion(&mut GAME_STATE.lock().unwrap()) {
            let _ = BROADCAST.send(ServerMessage::QuestCompleted { message });
        }
    }
}
💡 Completion check in Take/Drop handlers

check_quest_completion must also run after Take and Drop, since those are the moments the Star Fragment changes hands. Add this check inside both handler files — server/take_handler.rs and server/drop_handler.rs — right after the successful action and broadcast.

Both files already import super::{BROADCAST, GAME_STATE} (from Part 8); just add use super::quest; at the top, exactly like move_handler.rs. Then, after the ItemTaken/ItemDropped broadcast:

// Inside take_handler.rs, after the ItemTaken broadcast:
if let Some(message) =
    quest::check_quest_completion(&mut GAME_STATE.lock().unwrap())
{
    let _ = BROADCAST.send(
        ServerMessage::QuestCompleted { message },
    );
}

Same pattern in drop_handler.rs, after the ItemDropped broadcast. This ensures that if a player drops the Star Fragment in Town Square — or takes it while standing there — the completion triggers immediately.

mud-engine/src/game/server/mod.rs
        // ── Cleanup on disconnect ──
        let mut quest_event = None;
        let mut celebration = None;
        {
            let mut state = GAME_STATE.lock().unwrap();

            // Drop all carried items into the player's current room.
            // Read the room and carried items first (into owned values), then
            // mutate `ground` — the immutable borrow must end before the
            // mutable one starts.
            if let Some((room_id, carried)) = state
                .players
                .get(&id)
                .map(|p| (p.room, p.items.clone()))
            {
                let ground = state.ground.entry(room_id).or_default();
                for item in &carried {
                    if !ground.contains(item) {
                        ground.push(item.clone());
                    }
                }
            }

            state.players.remove(&id);

            // Re-evaluate the quest — a guardian may have left
            quest_event = quest::update_quest(&mut state);

            // Dropping carried items may have completed the quest
            celebration = quest::check_quest_completion(&mut state);
        }

        if let Some((active, message)) = quest_event {
            let _ = BROADCAST.send(ServerMessage::QuestEvent { active, message });
        }
        if let Some(message) = celebration {
            let _ = BROADCAST.send(ServerMessage::QuestCompleted { message });
        }
        let _ = BROADCAST.send(ServerMessage::PlayerLeft { id });
🎯 Why the direct vault descent check?

The movement handler has a special case for dir == "down" && current == 4:

if next.is_none() && dir == "down" && current == 4 {
    let q_active = state.quest.as_ref()
        .map(|q| q.previously_active).unwrap_or(false);
    if q_active {
        next = Some(9);
    }
}

Why is it needed? The vault room has exits = [] in Game.toml, so normal can_move can never route there. And update_quest adds the "down" exit to room 4's RoomInfo only after the move validation runs. The direct check guarantees that as long as the gate is open (previously_active), descending from Town Square always works. Ascending works the other way: update_quest adds the "up" exit to the vault, so can_move finds it.

Nothing here touches disk — it's all mutations on the in-memory GameState, flushed later by the autosave task.

Step 7 / 12