← All Workshops

MudEngine Part 6: Multiplayer

Step 16 / 19

Game Component — Template

Now add the rsx! block and closing brace. The template has three regions:

RegionWhat it renders
.game-layoutWorldGrid on the left, player sidebar on the right. The onkeydown handler maps arrow keys, WASD, and vim keys to send_move calls
.descriptionThe current room name and description, derived from my_info
DirectionPadThe D-pad at the bottom, wired to the same send_move closure

Append this to src/components/game.rs (after the send_move closure from the previous step), then add pub mod game; to src/components/mod.rs:

mud-engine/src/components/game.rs
    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());
                }
            },
            div { class: "grid-area",
                WorldGrid {
                    players: players,
                    my_id: my_id,
                    onmove: send_move,
                }
            }
            div { class: "sidebar",
                h2 { "⚔️ Adventurers" }
                for p in players.read().values() {
                    {
                        let is_me = *my_id.read() == p.id;
                        rsx! {
                            div {
                                key: "{p.id}",
                                class: if is_me { "player-entry me" } else { "player-entry" },
                                span { class: "player-name",
                                    "{p.name}"
                                    if is_me { " (you)" }
                                }
                                span { class: "player-room", "{ROOM_NAMES[p.room]}" }
                            }
                        }
                    }
                }
            }
        }
        if let Some(ref info) = my_info {
            div { class: "description",
                "{ROOM_NAMES[info.room]}"
                "\n"
                "{ROOM_DESCS[info.room]}"
            }
        }
        DirectionPad {
            onmove: send_move,
        }
    }
}
⚠️ Why the send is wrapped in spawn

socket.send(...) is an async function — it returns a Future that does nothing until it is polled. Calling it without await creates the future and immediately drops it. A dropped future never runs, so the move message would never leave the browser (clicking the D-pad would do nothing).

Registration worked because the receive side was correctly awaited (connect().await, recv().await). Only the fire-and-forget send was swallowed.

spawn(async move { ... }) hands the future to the Dioxus runtime, which polls it to completion. socket is Copy, so moving it into the async block is safe. The send_move closure is passed to the D-pad, the clickable room cards, and the keyboard shortcuts — so every navigation method actually transmits ClientMessage::Move, the server broadcasts PlayerMoved, and the grid and description update.

💡 How use_websocket works

use_websocket takes a closure that calls a server function (our mud_ws). The hook:

  1. Creates a reactive handle (WebsocketHandle) that manages the connection lifecycle
  2. The handle's .connect() method initiates the WebSocket upgrade on the server
  3. .send(msg) serializes the ClientMessage to JSON and sends it as a WebSocket frame
  4. .recv() awaits the next incoming frame and deserializes it to ServerMessage
  5. .status() returns the current connection state

When the use_future loop calls socket.connect().await, it establishes the connection. If the connection drops (server restart, network blip), the while let Ok(msg) loop exits and we retry by calling connect() again.

The closure inside use_websocket(move || mud_ws(name.clone(), ...)) re-runs only when its captured signals change. Since name is a derived String from player_name() (not a signal), it stays fixed for the component lifetime.

Message flow for a move:

Player clicks ▲  →  socket.send(Move { "north" })
                        │
                        ▼
              Server validates against EXITS[room]
                        │
                        ▼
              Broadcasts PlayerMoved { room: 1 }
                        │
                        ▼
         ┌──────────────┼──────────────┐
         ▼              ▼              ▼
      Alice         Bob (other    Charlie (other
      (sender)      tab)           tab)
         │              │              │
         ▼              ▼              ▼
    updates        updates        updates
    players map    players map    players map

The sender also receives the broadcast — we don't optimistically update the local grid. The server is the single source of truth for all players. This prevents desyncs and makes the game logic simple to reason about.

Step 16 / 19