← All Workshops

MudEngine Part 2: Single-Player REPL

Step 10 / 11

Faster lookups: HashMap for rooms and exits

The engine works, so let's make it faster. Both look() and go() currently do linear scans:

  • look() uses rooms.iter().find(...) to walk every room until it finds the player's id
  • go() loops over every exit tuple comparing direction strings

That is O(n) work per call — invisible with three rooms, but every room or exit you add makes the scan longer. Both scans can collapse to O(1) lookups, and HashMap is the idiomatic fit for both:

  • Rooms by id — HashMap<usize, Room> lets you fetch the current room directly with &self.rooms[&self.player_room]
  • Exits by direction — HashMap<String, usize> inside each Room makes moving a single room.exits.get(direction) lookup

Replace the Room struct, the World struct, and the impl World block:

mud-engine-repl/src/main.rs
use std::collections::HashMap;
use std::io::{self, Write};

struct Room {
    name: String,
    description: String,
    exits: HashMap<String, usize>,
}

struct World {
    rooms: HashMap<usize, Room>,
    player_room: usize,
}

impl World {
    fn new() -> Self {
        let rooms = HashMap::from([
            (
                1,
                Room {
                    name: "Town Square".into(),
                    description: "A bustling town square with a fountain at its center. Cobblestones gleam from the morning rain.".
                        into(),
                    exits: HashMap::from([("north".into(), 2), ("east".into(), 3)]),
                },
            ),
            (
                2,
                Room {
                    name: "Market Street".into(),
                    description: "A narrow lane lined with wooden stalls. The scent of fresh bread and spices hangs in the air.".
                        into(),
                    exits: HashMap::from([("south".into(), 1)]),
                },
            ),
            (
                3,
                Room {
                    name: "Temple Courtyard".into(),
                    description: "Ancient stone pillars surround a quiet courtyard. Moss clings to weathered statues.".
                        into(),
                    exits: HashMap::from([("west".into(), 1)]),
                },
            ),
        ]);
        World {
            rooms,
            player_room: 1,
        }
    }

    fn look(&self) -> String {
        let room = &self.rooms[&self.player_room];
        let mut out = String::new();
        out.push_str(&room.name);
        out.push('\n');
        out.push_str(&room.description);
        out.push_str("\n\nExits:");
        let mut dirs: Vec<&String> = room.exits.keys().collect();
        dirs.sort();
        for dir in dirs {
            out.push(' ');
            out.push_str(dir);
        }
        out
    }

    fn go(&mut self, direction: &str) -> String {
        let room = &self.rooms[&self.player_room];
        if let Some(&id) = room.exits.get(direction) {
            self.player_room = id;
            return self.look();
        }
        format!("You cannot go {} from here.", direction)
    }
}
🔍 What changed
Before (Vec)After (HashMap)Why it helps
rooms.iter().find(...) — linear scan&self.rooms[&self.player_room] — direct indexO(n) scan becomes O(1)
for (dir, id) in &room.exits { if dir == ... }room.exits.get(direction) — Option<&usize>O(n) scan becomes O(1)
room needs an id field to scan bythe player position is the map keyno redundant data
exits print in insertion orderexit list is sorted before printingdeterministic output

if let Some(&id) = room.exits.get(direction) pattern-matches the destination id out of the Option, updates player_room, and describes the new room — all in one step. If the direction is missing, the program falls through to the cannot go message, just like before.

HashMap also owns no insertion order, so displaying exits can no longer rely on the order they were added. look() collects the keys into a Vec<&String>, sorts them, and prints alphabetically — a tiny, explicit trade-off for the speed.

The &self.rooms[&self.player_room] index uses Index, which panics if the key is missing. Here player_room is only ever set to an id that exists, so it is safe — the exit lookup uses get(), the non-panicking variant, because the direction string comes from the player and may not exist.

Rebuild and verify
cargo run
💡 Adding rooms, HashMap edition

The "Extend the world" tip from earlier used vec![...]. With a map, add a (id, Room { ... }) entry to the HashMap::from([...]) array instead:

(
    4,
    Room {
        name: "Dark Forest".into(),
        description: "Twisted trees block out the sky. Eyes gleam in the shadows.".into(),
        exits: HashMap::from([("south".into(), 2)]),
    },
),

Each room is now a key-value pair: the id is the key, the Room is the value.

Step 10 / 11