← All Workshops

MudEngine Part 11: Peer-to-Peer with iroh

Step 11 / 14

Swap the transport in Game

The component keeps every signal, every panel, the quest UI, and the whole RSX from Parts 8–10. Only the transport changes: use_websocket(mud_ws(...)) and the socket.recv() loop are replaced by net::connect(...) and an mpsc event receiver. The diff is small and visible:

  • Connect once. use_future calls net::connect(role, player_name, host_id) (a None host id means I am the host), stores the returned Session in a signal, and immediately broadcasts a Join handshake.
  • Receive. while let Some(msg) = events.recv().await — the same match msg on ServerMessage variants as before.
  • Send. Actions are pushed onto the Session's send queue instead of awaited on a socket: let _ = s.send.send((s.my_id.clone(), msg));.
  • Status, not silence. While connecting, a net-banner shows "Connecting to the mesh…". Once connected, the host shows its node id to share; a joiner shows the host id it reached. Failures render an error-screen instead of a dead WebSocket reconnect loop.
mud-engine/src/components/game.rs
use std::collections::HashMap;

use crate::components::direction_pad::DirectionPad;
use crate::components::world_grid::WorldGrid;
use crate::game::messages::{ClientMessage, PlayerInfo, RoomInfo, ServerMessage};
use crate::game::net::{self, Role, Session};
use dioxus::prelude::*;

/// A chat line rendered in the room-chat panel. Lives only on the client —
/// never serialized. The `room` field filters messages to same-room chat only.
#[derive(Clone, Debug)]
struct ChatMessage {
    from: String,
    message: String,
    room: usize,
    is_mine: bool,
}

#[derive(Clone, Debug)]
struct QuestDisplay {
    name: String,
    active: bool,
    completed: bool,
    guardians: Vec<QuestGuardianDisplay>,
}

#[derive(Clone, Debug)]
struct QuestGuardianDisplay {
    label: String,
    room_id: usize,
}

/// The fixed-position player roster: every connected player, their current
/// room, and what items they carry. Re-renders only when its signal props change.
#[component]
fn FloatingPlayerList(
    players: ReadSignal<HashMap<String, PlayerInfo>>,
    rooms: ReadSignal<HashMap<usize, RoomInfo>>,
    my_id: ReadSignal<String>,
) -> Element {
    rsx! {
        div { class: "floating-player-list",
            h2 { class: "fpl-title", "⚔️ Adventurers" }
            div { class: "fpl-scroll",
                for p in players.read().values() {
                    {
                        let is_me = *my_id.read() == p.id;
                        let room_name = rooms.read()
                            .get(&p.room)
                            .map(|r| r.name.clone())
                            .unwrap_or_default();
                        rsx! {
                            div {
                                key: "{p.id}",
                                class: if is_me { "fpl-entry me" } else { "fpl-entry" },
                                div { class: "fpl-name",
                                    "{p.name}"
                                    if is_me { " (you)" }
                                }
                                div { class: "fpl-room", "{room_name}" }
                                if !p.items.is_empty() {
                                    div { class: "fpl-items",
                                        for item in &p.items {
                                            span { class: "fpl-item", "{item}" }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/// The current player's carried items.
#[component]
fn InventoryPanel(
    players: ReadSignal<HashMap<String, PlayerInfo>>,
    my_id: ReadSignal<String>,
    ondrop: Callback<String>,
) -> Element {
    let my_info = {
        let p = players.read();
        let id = my_id.read();
        p.get(&*id).cloned()
    };

    rsx! {
        div { class: "inventory-panel",
            h3 { class: "inv-title", "🎒 Inventory" }
            if let Some(ref info) = my_info {
                if info.items.is_empty() {
                    div { class: "inv-empty", "Empty" }
                } else {
                    for item in info.items.clone() {
                        div {
                            key: "{item}",
                            class: "inv-item",
                            onclick: move |_| ondrop.call(item.clone()),
                            "{item}",
                        }
                    }
                }
            }
        }
    }
}

#[component]
pub fn Game(role: Role, player_name: String, host_id: String) -> Element {
    let mut players = use_signal::<HashMap<String, PlayerInfo>>(HashMap::new);
    let mut my_id = use_signal(String::new);
    let mut rooms = use_signal::<HashMap<usize, RoomInfo>>(HashMap::new);
    let mut chat_messages = use_signal::<Vec<ChatMessage>>(Vec::new);
    let mut command_input = use_signal(String::new);
    let mut quest_display = use_signal::<Option<QuestDisplay>>(|| None);
    let mut vault_open = use_signal(|| false);

    // The transport handle once the mesh is up (None while connecting), plus
    // any error that made joining impossible.
    let mut session = use_signal::<Option<Session>>(|| None);
    let mut error = use_signal::<Option<String>>(|| None);

    // ── Connection + message receive loop ──
    // `players`, `my_id`, `rooms`, `chat_messages`, `session`, and `error`
    // are `Signal`s (Copy), so the `move` closure captures and mutates them
    // by value — no clones needed.
    use_future(move || {
        let player_name = player_name.clone();
        let host_id = host_id.clone();
        async move {
        // Only joining clients dial a host — the host itself is the mesh.
        let host_id = if role == Role::Host { None } else { Some(host_id) };
        match net::connect(role, player_name, host_id).await {
            Ok((session_info, mut events)) => {
                session.set(Some(session_info.clone()));

                // Join handshake: the host registers us and answers with a
                // `State` snapshot (clients apply it only when `your_id`
                // matches our own id).
                let _ = session_info.send.send((
                    session_info.my_id.clone(),
                    ClientMessage::Join {
                        name: session_info.my_name.clone(),
                    },
                ));

                while let Some(msg) = events.recv().await {
                    match msg {
                    ServerMessage::State {
                        players: p,
                        your_id,
                        rooms: r,
                        quest,
                    } => {
                        let mut map = players.write();
                        map.clear();
                        for pl in p {
                            map.insert(pl.id.clone(), pl);
                        }
                        my_id.set(your_id);

                        let mut room_map = rooms.write();
                        room_map.clear();
                        for room in r {
                            room_map.insert(room.id, room);
                        }

                        // Render the quest panel straight from the server data
                        if let Some(q) = quest {
                            quest_display.set(Some(QuestDisplay {
                                name: q.name,
                                active: q.active,
                                completed: q.completed,
                                guardians: q
                                    .guardians
                                    .into_iter()
                                    .map(|g| QuestGuardianDisplay {
                                        label: g.label,
                                        room_id: g.room_id,
                                    })
                                    .collect(),
                            }));
                            vault_open.set(q.active);
                        }
                    }
                    ServerMessage::PlayerJoined(pl) | ServerMessage::PlayerMoved(pl) => {
                        // PlayerMoved carries the real inventory now, so no preserving
                        players.write().insert(pl.id.clone(), pl);
                    }
                    ServerMessage::PlayerLeft { id } => {
                        players.write().remove(&id);
                    }
                    ServerMessage::Chat {
                        from,
                        message,
                        room,
                    } => {
                        let mut msgs = chat_messages.write();
                        msgs.push(ChatMessage {
                            from,
                            message,
                            room,
                            is_mine: false,
                        });
                        if msgs.len() > 50 {
                            msgs.remove(0);
                        }
                    }
                    ServerMessage::ItemTaken {
                        player_id,
                        player_name,
                        item,
                    } => {
                        {
                            let mut map = players.write();
                            if let Some(p) = map.get_mut(&player_id) {
                                p.items.push(item.clone());
                            }
                        }

                        // Remove the item from the ground of the player's room
                        let player_room = players.read().get(&player_id).map(|p| p.room);
                        if let Some(room_id) = player_room {
                            let mut room_map = rooms.write();
                            if let Some(r) = room_map.get_mut(&room_id) {
                                r.items.retain(|i| i != &item);
                            }
                        }

                        let mut msgs = chat_messages.write();
                        msgs.push(ChatMessage {
                            from: "⚡ System".into(),
                            message: format!("{} picks up {}.", player_name, item),
                            room: 0,
                            is_mine: false,
                        });
                    }
                    ServerMessage::ItemDropped {
                        player_id,
                        player_name,
                        item,
                        room,
                    } => {
                        {
                            let mut map = players.write();
                            if let Some(p) = map.get_mut(&player_id) {
                                p.items.retain(|i| i != &item);
                            }
                        }

                        {
                            let mut room_map = rooms.write();
                            if let Some(r) = room_map.get_mut(&room) {
                                r.items.push(item.clone());
                            }
                        }

                        let mut msgs = chat_messages.write();
                        msgs.push(ChatMessage {
                            from: "⚡ System".into(),
                            message: format!("{} drops {}.", player_name, item),
                            room: 0,
                            is_mine: false,
                        });
                    }
                    ServerMessage::QuestEvent { active, message } => {
                        vault_open.set(active);
                        if let Some(ref mut qd) = *quest_display.write() {
                            qd.active = active;
                        }

                        let mut msgs = chat_messages.write();
                        msgs.push(ChatMessage {
                            from: "⚡ Quest".into(),
                            message,
                            room: 0,
                            is_mine: false,
                        });
                    }
                    ServerMessage::QuestCompleted { message } => {
                        if let Some(ref mut qd) = *quest_display.write() {
                            qd.completed = true;
                            qd.active = false;
                        }
                        vault_open.set(false);

                        let mut msgs = chat_messages.write();
                        msgs.push(ChatMessage {
                            from: "👑 King Aldric".into(),
                            message,
                            room: 0,
                            is_mine: false,
                        });
                    }
                }
            }

                // The host stopped answering / the mesh dropped us.
                error.set(Some("Lost the connection to the host.".into()));
            }
            Err(e) => error.set(Some(e)),
        }
        }
    });

    let my_info = {
        let p = players.read();
        let id = my_id.read();
        p.get(&*id).cloned()
    };

    // One way to send a client message: push it onto the session's send queue
    // (the host's engine — or the relay, in step 2 — answers with events).
    let send = move |msg: ClientMessage| {
        if let Some(s) = session.with(|opt| opt.clone()) {
            let _ = s.send.send((s.my_id.clone(), msg));
        }
    };
    let send_move = move |direction: String| {
        send(ClientMessage::Move { direction });
    };

    // the rsx! block follows below

    rsx! {
        div { class: "game-layout",
            tabindex: "0",
            onkeydown: move |e| {
                let dir = match e.key() {
                    Key::ArrowUp => Some("north"),
                    Key::ArrowDown => Some("south"),
                    Key::ArrowLeft => Some("west"),
                    Key::ArrowRight => Some("east"),
                    Key::Character(c) => match c.as_str() {
                        "w" | "k" => Some("north"),
                        "s" | "j" => Some("south"),
                        "a" | "h" => Some("west"),
                        "d" | "l" => Some("east"),
                        _ => None,
                    },
                    _ => None,
                };
                if let Some(d) = dir {
                    e.prevent_default();
                    send_move(d.to_string());
                }
            },
            // ── Connection status: error screen, else a live banner ──
            if let Some(ref err) = *error.read() {
                div { class: "error-screen",
                    h1 { "😵 Connection problem" }
                    p { "{err}" }
                    p { "Close this window and start again." }
                }
            } else {
                match session.read().as_ref() {
                    None => rsx! {
                        div { class: "net-banner",
                            span { "⏳ Connecting to the mesh…" }
                        }
                    },
                    Some(s) if s.role == Role::Host => rsx! {
                        div { class: "net-banner hosting",
                            span { "🖥️ Hosting. Share your node id so friends can join:" }
                            code { class: "node-id", "{s.node_id}" }
                        }
                    },
                    Some(s) => rsx! {
                        div { class: "net-banner joined",
                            span { "✅ Joined host " }
                            code { class: "node-id", "{s.host_id}" }
                        }
                    },
                }
                // ── Left: 3×3 grid ──
                div { class: "grid-area",
                div { class: "world-grid",
                    WorldGrid {
                        players: players,
                        my_id: my_id,
                        rooms: rooms,
                        onmove: send_move,
                    }
                }

                // ── Description panel + items on the ground ──
                if let Some(ref info) = my_info {
                    if let Some(rd) = rooms.read().get(&info.room).cloned() {
                        div { class: "description",
                            div { class: "desc-title", "{rd.name}" }
                            div { class: "desc-text", "{rd.description}" }
                        }
                        if !rd.items.is_empty() {
                            div { class: "room-items",
                                h3 { "📦 Items here" }
                                for item in rd.items.clone() {
                                    div {
                                        class: "room-item",
                                        onclick: move |_| send(ClientMessage::Take { item: item.clone() }),
                                        "{item}",
                                    }
                                }
                            }
                        }
                    }
                }
            }
            }

            // ── Right: floating player list (replaces the old sidebar) ──
            FloatingPlayerList {
                players: players,
                rooms: rooms,
                my_id: my_id,
            }

            // ── Quest panel (between grid and bottom-area) ──
            if let Some(ref quest) = *quest_display.read() {
                if quest.completed {
                    div { class: "quest-panel completed",
                        div { class: "quest-title", "👑 Quest Complete: {quest.name}" }
                        div { class: "quest-complete-msg",
                            "King Aldric has the Star Fragment! The realm is saved!"
                        }
                    }
                } else {
                    div { class: "quest-panel",
                        div { class: "quest-title",
                            if quest.active { "🔓 " } else { "🔒 " }
                            "{quest.name}"
                        }
                        div { class: "quest-phase-hint",
                            if quest.active {
                                "Portal open! A hero must descend, retrieve the Star Fragment, and bring it to the King."
                            } else {
                                "Place two heroes on the pedestals to open the portal."
                            }
                        }
                        div { class: "quest-guardians",
                            for g in &quest.guardians {
                                {
                                    // Occupancy is derived live from the players
                                    // signal, so the chips stay accurate as heroes move.
                                    let g_active = players.read()
                                        .values()
                                        .any(|p| p.room == g.room_id);
                                    rsx! {
                                        div {
                                            key: "{g.label}",
                                            class: if g_active {
                                                "quest-guardian active"
                                            } else {
                                                "quest-guardian"
                                            },
                                            if g_active { "✅ " } else { "⏳ " }
                                            "{g.label}"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // ── King Aldric NPC dialog (shown in Town Square) ──
            if let Some(ref info) = my_info {
                if info.room == 4 {
                    div { class: "npc-dialog",
                        div { class: "npc-name", "👑 King Aldric" }
                        if quest_display.read().as_ref().map(|q| q.completed).unwrap_or(false) {
                            div { class: "npc-text",
                                ""The Star Fragment glows with ancient power! You have my eternal gratitude, brave adventurers!""
                            }
                        } else if info.items.contains(&"star fragment".into()) {
                            div { class: "npc-text highlight",
                                ""You have it! The Star Fragment! Quick, hand it to me so I can restore the wards!""
                            }
                        } else if *vault_open.read() {
                            div { class: "npc-text",
                                ""The portal is open! Someone must venture below and retrieve the Star Fragment!""
                            }
                        } else {
                            div { class: "npc-text",
                                ""The Ancient Vault lies sealed. I need two brave souls to stand on the Sun and Moon Pedestals to open the way.""
                            }
                        }
                    }
                }
            }

            // ── Quest action buttons ──
            if *vault_open.read() {
                if let Some(ref info) = my_info {
                    if info.room == 4 {
                        div { class: "quest-actions",
                            button {
                                class: "quest-btn",
                                onclick: move |_| {
                                    send(ClientMessage::Move { direction: "down".into() });
                                },
                                "⬇ Descend into the Ancient Vault"
                            }
                        }
                    }
                }
            }

            if let Some(ref info) = my_info {
                if info.room == 9 {
                    div { class: "quest-actions",
                        button {
                            class: "quest-btn",
                            onclick: move |_| {
                                send(ClientMessage::Move { direction: "up".into() });
                            },
                            "⬆ Ascend to Town Square"
                        }
                    }
                }
            }

            // ── Bottom row: chat + input + controls ──
            div { class: "bottom-area",
                // Chat panel
                div { class: "chat-panel",
                    onclick: move |_| {
                        _ = dioxus::document::eval(
                            "document.querySelector('.command-input')?.focus();",
                        );
                    },
                    div { class: "chat-header", "💬 Room Chat" }
                    div { class: "chat-scroll",
                        if chat_messages.read().is_empty() {
                            div { class: "chat-empty",
                                "Say something with: say hello"
                            }
                        }
                        for msg in chat_messages.read().iter() {
                            if my_info.as_ref().is_some_and(|info| msg.room == info.room)
                                || msg.from.starts_with("⚡")
                            {
                                div { class: "chat-msg",
                                    if msg.from.starts_with("⚡") {
                                        span { class: "chat-system", "{msg.message}" }
                                    } else {
                                        span { class: "chat-from", "{msg.from}: " }
                                        span { class: "chat-text", "{msg.message}" }
                                    }
                                }
                            }
                        }
                    }
                }

                // Command input + D-pad
                div { class: "controls-area",
                    div { class: "command-row",
                        input {
                            class: "command-input",
                            value: "{command_input}",
                            oninput: move |e| command_input.set(e.value()),
                            onkeydown: move |e| {
                                // Don't let this keystroke bubble up to the movement handler:
                                // w/a/s/d/h/j/k/l need to be *typed*, not move the player.
                                e.stop_propagation();
                                if e.key() == Key::Enter {
                                    let cmd = command_input.read().trim().to_string();
                                    if !cmd.is_empty() {
                                        if let Some((verb, rest)) = cmd.split_once(char::is_whitespace)
                                            .map(|(v, r)| (v.to_lowercase(), r.trim().to_string()))
                                        {
                                            match verb.as_str() {
                                                "say" | "'" => {
                                                    send(ClientMessage::Say { message: rest });
                                                }
                                                "take" | "get" => {
                                                    send(ClientMessage::Take { item: rest });
                                                }
                                                "drop" => {
                                                    send(ClientMessage::Drop { item: rest });
                                                }
                                                _ => {}
                                            }
                                        }
                                        command_input.set(String::new());
                                    }
                                }
                            },
                            placeholder: "Type 'say hello', 'take sword', 'drop map'...",
                        }
                    }

                    DirectionPad {
                        onmove: send_move,
                    }
                }

                // Inventory panel
                InventoryPanel {
                    players: players,
                    my_id: my_id,
                    ondrop: move |item: String| send(ClientMessage::Drop { item }),
                }
            }
        }
    }
}
🔍 This is the whole capstone in one sentence

Game renders whatever the mesh delivers; the engine decides; the mesh just carries bytes. The UI never learns whether it talks to Axum, iroh, or (in step 2) a relay — net::connect returns the same (Session, receiver) contract every time.

Step 11 / 14