← All Workshops

MudEngine Part 6: Multiplayer

Step 15 / 19

Game Component — Logic

The Game component is the heart of the client. It connects to the server, tracks all players, and composes the UI. We build it in two steps: first the logic, then the template.

What the logic does

PartPurpose
Signalsplayers (HashMap of all connected players) and my_id (our server-assigned ID) store the authoritative state
WebSocketuse_websocket returns a Copy handle that manages the connection lifecycle
Message loopuse_future calls connect() then loops on recv(), matching each ServerMessage to update the signals
send_moveA single closure shared by D-pad, clickable rooms, and keyboard. Wraps socket.send() in spawn() so the async future is actually polled
Focususe_effect auto-focuses .game-layout on mount so keyboard shortcuts work immediately

Create src/components/game.rs with the logic half — everything from imports through the send_move closure. The rsx! template comes in the next step:

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, ServerMessage};
use crate::game::room_data::{ROOM_DESCS, ROOM_NAMES};
use crate::game::server::mud_ws;
use dioxus::prelude::*;
use dioxus_fullstack::{use_websocket, WebSocketOptions};

#[component]
pub fn Game(name: String) -> Element {
    let mut players = use_signal::<HashMap<String, PlayerInfo>>(|| HashMap::new());
    let mut my_id = use_signal(|| String::new());

    let mut socket = use_websocket(move || {
        mud_ws(name.clone(), WebSocketOptions::new())
    });

    // ── Message loop ──
    {
        let mut players = players.clone();
        let mut my_id = my_id.clone();
        use_future(move || async move {
            loop {
                _ = socket.connect().await;
                while let Ok(msg) = socket.recv().await {
                    match msg {
                        ServerMessage::State { players: p, your_id } => {
                            let mut map = players.write();
                            map.clear();
                            for pl in p {
                                map.insert(pl.id.clone(), pl);
                            }
                            my_id.set(your_id);
                        }
                        ServerMessage::PlayerJoined(pl)
                        | ServerMessage::PlayerMoved(pl) => {
                            players.write().insert(pl.id.clone(), pl);
                        }
                        ServerMessage::PlayerLeft { id } => {
                            players.write().remove(&id);
                        }
                    }
                }
            }
        });
    }

    // Focus the game area on mount so keyboard shortcuts work immediately
    use_effect(move || {
        let _ = document::eval("document.querySelector('.game-layout')?.focus()");
    });

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

    // The single way to send a move: spawn the async send so it gets polled
    let send_move = move |direction: String| {
        spawn(async move {
            let _ = socket.send(ClientMessage::Move { direction }).await;
        });
    };
Step 15 / 19