← All Workshops

MudEngine Part 11: Peer-to-Peer with iroh

Step 6 / 14

The engine, transport-agnostic

The old server handlers wrapped GameState in a Mutex and wrote results to WebSocket connections. The new GameEngine keeps the same state and the same quest logic, but its methods return Vec<ServerMessage> — the things that should be broadcast — and never touch a socket. Publishing is the network layer's job. That single responsibility split is the whole architectural punch of this part.

GameEngine::load() seeds the world, the live ground, and the quest config from Game.toml + Players.toml, exactly like Axum's startup did. Then:

  • join(&mut self, id, name) — register a player and answer with PlayerJoined + a targeted State snapshot
  • leave(&mut self, id) — drop carried items into the player's room, re-run the quest, broadcast PlayerLeft (the mesh tells the engine who disappeared)
  • handle(&mut self, id, msg) — dispatch any ClientMessage (Join included)
  • move_player / say / take / drop — Parts 7–9 behavior, quest-aware
  • state_message(&mut self, your_id) — the full-world snapshot for one player

The quest helpers (update_quest, check_quest_completion) are unchanged from Part 9 — this file is the server handlers collapsed into methods, not new game rules:

mud-engine/src/game/engine.rs
use super::messages::{PlayerInfo, QuestGuardianInfo, QuestInfo, ServerMessage};
use super::persistence::{self, Exit, GameState, QuestStatus};

/// How often the in-memory game state is flushed to Players.toml.
/// Configurable — crank it down (e.g. 5s) while testing, keep it at
/// 60s in production. Crashes lose at most one interval of changes.
pub const AUTOSAVE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);

/// The authoritative game engine. Transport-agnostic: it owns the
/// `GameState` and answers every client request with the `ServerMessage`s
/// that the still-networking layer should broadcast. It never touches
/// sockets, gossip topics, or the WebSocket relay.
pub struct GameEngine {
    pub state: GameState,
}

impl GameEngine {
    /// Load the world, the live player state, and the quest config from disk,
    /// exactly like the old Axum-server startup did.
    pub fn load() -> Self {
        let live = persistence::load_players("Players.toml");

        // Seed the ground from the static item layout, then apply live changes
        let mut ground = persistence::seed_ground("Game.toml");
        for (room, items) in live.ground {
            ground.insert(room, items);
        }

        // Static quest config from Game.toml + the persisted completion flag
        let quest = persistence::load_quest("Game.toml").map(|config| QuestStatus {
            config,
            previously_active: false,
            completed: live.quest_completed.unwrap_or(false),
        });

        Self {
            state: GameState {
                rooms: persistence::load_world("Game.toml"),
                players: live.players,
                ground,
                quest,
            },
        }
    }

    /// Handle a new player joining. Returns the messages to broadcast:
    /// a `PlayerJoined` for everyone, and a `State` snapshot targeted at
    /// the joining player (clients apply it only when `your_id` matches).
    pub fn join(&mut self, player_id: &str, player_name: &str) -> Vec<ServerMessage> {
        self.state.players.insert(
            player_id.to_string(),
            PlayerInfo {
                id: player_id.to_string(),
                name: player_name.to_string(),
                room: 4,
                items: Vec::new(),
            },
        );

        vec![
            ServerMessage::PlayerJoined(PlayerInfo {
                id: player_id.to_string(),
                name: player_name.to_string(),
                room: 4,
                items: Vec::new(),
            }),
            self.state_message(player_id),
        ]
    }

    /// The player's display name, looked up live from the roster so each
    /// handler can echo it (chat "from", item messages, move broadcasts)
    /// without the network layer having to track it.
    fn name_of(&self, player_id: &str) -> String {
        self.state
            .players
            .get(player_id)
            .map(|p| p.name.clone())
            .unwrap_or_else(|| player_id.to_string())
    }

    /// Handle a player leaving (peer dropped from the gossip mesh).
    /// Drops their carried items into their room and re-evaluates the quest.
    pub fn leave(&mut self, player_id: &str) -> Vec<ServerMessage> {
        let mut messages = Vec::new();

        // Drop all carried items into the player's current room.
        if let Some((room_id, carried)) =
            self.state.players.get(player_id).map(|p| (p.room, p.items.clone()))
        {
            let ground = self.state.ground.entry(room_id).or_default();
            for item in &carried {
                if !ground.contains(item) {
                    ground.push(item.clone());
                }
            }
        }

        self.state.players.remove(player_id);

        if let Some((active, message)) = update_quest(&mut self.state) {
            messages.push(ServerMessage::QuestEvent { active, message });
        }
        if let Some(message) = check_quest_completion(&mut self.state) {
            messages.push(ServerMessage::QuestCompleted { message });
        }
        messages.push(ServerMessage::PlayerLeft {
            id: player_id.to_string(),
        });

        messages
    }

    /// Route one `ClientMessage` from a known player through its handler.
    pub fn handle(&mut self, player_id: &str, msg: super::messages::ClientMessage) -> Vec<ServerMessage> {
        match msg {
            super::messages::ClientMessage::Join { name } => self.join(player_id, &name),
            super::messages::ClientMessage::Move { direction } => self.move_player(player_id, &direction),
            super::messages::ClientMessage::Say { message } => self.say(player_id, &message),
            super::messages::ClientMessage::Take { item } => self.take(player_id, &item),
            super::messages::ClientMessage::Drop { item } => self.drop(player_id, &item),
        }
    }

    /// Handle a 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 move_player(&mut self, player_id: &str, direction: &str) -> Vec<ServerMessage> {
        let player_name = self.name_of(player_id);
        // A player might act before the host registered their `Join` — ignore.
        let Some(current) = self.state.players.get(player_id).map(|p| p.room) else {
            return Vec::new();
        };

        let dir = match direction {
            "n" => "north",
            "s" => "south",
            "e" => "east",
            "w" => "west",
            "down" | "d" => "down",
            "up" | "u" => "up",
            d => d,
        };

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

        // Direct vault descent while the gate is open.
        if next.is_none() && dir == "down" && current == 4 {
            let q_active = self
                .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) => {
                self.state.players.get_mut(player_id).unwrap().room = room;
                update_quest(&mut self.state)
            }
            None => None,
        };

        let Some(room) = next else {
            return Vec::new();
        };

        // Real inventory, so the roster stays accurate
        let items = self
            .state
            .players
            .get(player_id)
            .map(|p| p.items.clone())
            .unwrap_or_default();

        let mut messages = vec![ServerMessage::PlayerMoved(PlayerInfo {
            id: player_id.to_string(),
            name: player_name.to_string(),
            room,
            items,
        })];

        if let Some((active, message)) = quest_event {
            messages.push(ServerMessage::QuestEvent { active, message });
        }

        // Moving may have carried the Star Fragment home
        if let Some(message) = check_quest_completion(&mut self.state) {
            messages.push(ServerMessage::QuestCompleted { message });
        }

        messages
    }

    /// Handle a chat message: read the player's current room so clients can
    /// filter to same-room chat only.
    pub fn say(&mut self, player_id: &str, message: &str) -> Vec<ServerMessage> {
        let Some(current_room) = self.state.players.get(player_id).map(|p| p.room) else {
            return Vec::new();
        };

        vec![ServerMessage::Chat {
            from: self.name_of(player_id),
            message: message.to_string(),
            room: current_room,
        }]
    }

    /// Handle a take request: validate the item is on the floor of the player's
    /// current room, move it into their inventory, and return `ItemTaken` if it
    /// succeeded.
    pub fn take(&mut self, player_id: &str, item: &str) -> Vec<ServerMessage> {
        let mut messages = Vec::new();

        let room_id = match self.state.players.get(player_id).map(|p| p.room) {
            Some(room) => room,
            None => return messages,
        };

        let mut success = false;
        if let Some(items) = self.state.ground.get_mut(&room_id)
            && let Some(pos) = items.iter().position(|i| i == item)
        {
            items.remove(pos);
            self.state
                .players
                .get_mut(player_id)
                .unwrap()
                .items
                .push(item.to_string());
            success = true;
        }

        if success {
            messages.push(ServerMessage::ItemTaken {
                player_id: player_id.to_string(),
                player_name: self.name_of(player_id),
                item: item.to_string(),
            });

            // Taking may be the moment the Star Fragment reaches the King
            if let Some(message) = check_quest_completion(&mut self.state) {
                messages.push(ServerMessage::QuestCompleted { message });
            }
        }

        messages
    }

    /// Handle a drop request: validate the player is carrying the item, move it
    /// onto the floor of their current room, and return `ItemDropped` if it
    /// succeeded.
    pub fn drop(&mut self, player_id: &str, item: &str) -> Vec<ServerMessage> {
        let mut messages = Vec::new();

        let room_id = match self.state.players.get(player_id).map(|p| p.room) {
            Some(room) => room,
            None => return messages,
        };

        let mut success = false;
        if let Some(pos) = self
            .state
            .players
            .get_mut(player_id)
            .unwrap()
            .items
            .iter()
            .position(|i| i == item)
        {
            self.state.players.get_mut(player_id).unwrap().items.remove(pos);
            self.state.ground.entry(room_id).or_default().push(item.to_string());
            success = true;
        }

        if success {
            messages.push(ServerMessage::ItemDropped {
                player_id: player_id.to_string(),
                player_name: self.name_of(player_id),
                item: item.to_string(),
                room: room_id,
            });

            // Dropping may be the moment the Star Fragment reaches the King
            if let Some(message) = check_quest_completion(&mut self.state) {
                messages.push(ServerMessage::QuestCompleted { message });
            }
        }

        messages
    }

    /// Build the full-state snapshot a newly-joined player needs to render
    /// the whole world. `your_id` lets every client decide whether a given
    /// `State` message is addressed to it (broadcasts go to everyone).
    pub fn state_message(&self, your_id: &str) -> ServerMessage {
        let rooms: Vec<_> = self
            .state
            .rooms
            .iter()
            .map(|r| {
                let mut room = r.clone();
                room.items = self.state.ground.get(&r.id).cloned().unwrap_or_default();
                room
            })
            .collect();

        ServerMessage::State {
            players: self.state.players.values().cloned().collect(),
            your_id: your_id.to_string(),
            rooms,
            quest: self.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: self.state.players.values().any(|p| p.room == g.room_id),
                    })
                    .collect(),
            }),
        }
    }
}

// ── Quest logic — unchanged from the Parts 8–9 server ──

/// Evaluate quest conditions and mutate game state accordingly.
/// Returns the event to broadcast, or None if nothing changed.
fn update_quest(state: &mut GameState) -> Option<(bool, String)> {
    let quest = state.quest.as_mut()?;

    // Once the fragment reached the King, the quest is won for good.
    if quest.completed {
        return None;
    }

    // Both pedestals need at least one player — and a second player exists.
    let all_occupied = quest
        .config
        .guardians
        .iter()
        .all(|g| state.players.values().any(|p| p.room == g.room_id));

    let now_active = all_occupied && state.players.len() >= 2;

    if now_active == quest.previously_active {
        return None; // no change — nothing to broadcast
    }

    quest.previously_active = now_active;

    if now_active {
        // Open the portal: room 4 gains a "down" exit to the vault,
        // and the vault gains an "up" exit back to room 4.
        let reward = &quest.config.reward;
        if let Some(room) = state
            .rooms
            .iter_mut()
            .find(|r| r.id == reward.source_room_id)
            && !room.exits.iter().any(|e| e.direction == reward.direction)
        {
            room.exits.push(Exit {
                direction: reward.direction.clone(),
                destination: reward.target_room_id,
            });
        }
        if let Some(room) = state
            .rooms
            .iter_mut()
            .find(|r| r.id == reward.target_room_id)
            && !room.exits.iter().any(|e| e.direction == "up")
        {
            room.exits.push(Exit {
                direction: "up".into(),
                destination: reward.source_room_id,
            });
        }
        Some((
            true,
            format!(
                "☀️🌙 The Twin Guardians are united! A shimmering portal opens in {}!",
                state
                    .rooms
                    .iter()
                    .find(|r| r.id == reward.source_room_id)
                    .map(|r| &r.name[..])
                    .unwrap_or("the source room")
            ),
        ))
    } else {
        // Close the portal and teleport anyone in the vault back home.
        let reward = &quest.config.reward;
        let source_id = reward.source_room_id;
        if let Some(room) = state.rooms.iter_mut().find(|r| r.id == source_id) {
            room.exits.retain(|e| e.direction != reward.direction);
        }
        if let Some(room) = state
            .rooms
            .iter_mut()
            .find(|r| r.id == reward.target_room_id)
        {
            room.exits.retain(|e| e.direction != "up");
        }

        let victims: Vec<String> = state
            .players
            .iter()
            .filter(|(_, p)| p.room == reward.target_room_id)
            .map(|(id, _)| id.clone())
            .collect();
        for victim_id in &victims {
            if let Some(player) = state.players.get_mut(victim_id) {
                player.room = source_id;
            }
        }

        Some((
            false,
            format!(
                "🌙☀️ The Twin Guardians part ways! The portal to the {} seals shut!",
                reward.target_name
            ),
        ))
    }
}

/// Check whether the retrieval item has arrived in the completion room.
/// If so, mark the quest completed and return a celebration message.
fn check_quest_completion(state: &mut GameState) -> Option<String> {
    let quest = state.quest.as_mut()?;
    if quest.completed {
        return None;
    }

    let item = &quest.config.retrieval_item;
    let room_id = quest.config.completion_room;

    // On the floor? (the live ground map, not the static Game.toml rooms)
    let on_floor = state
        .ground
        .get(&room_id)
        .is_some_and(|items| items.iter().any(|i| i == item));

    // In a player's inventory while they stand in the completion room?
    let in_inventory = state
        .players
        .values()
        .any(|p| p.room == room_id && p.items.iter().any(|i| i == item));

    if on_floor || in_inventory {
        quest.completed = true;
        Some(format!(
            "👑 King Aldric beams with joy! 'The Star Fragment is returned! The realm is saved!' All hail the heroes who reclaimed the {}!",
            item
        ))
    } else {
        None
    }
}
🔍 What moved where
Part 9 server filePart 11 home
server/mod.rs (GAME_STATE, ws setup)deleted — replaced by net.rs glue
server/move_handler.rsGameEngine::move_player
server/say_handler.rsGameEngine::say
server/take_handler.rsGameEngine::take
server/drop_handler.rsGameEngine::drop
server/quest.rsupdate_quest / check_quest_completion (free fns)
connection-lifecycle codeGameEngine::join / leave + PlayerJoined/PlayerLeft
Step 6 / 14