Ruby Mud Is a State Machine Wearing a Text Adventure Costume

A 300-line Ruby framework where controllers are game states, commands are whitelisted methods, and a Telnet server runs on nothing but sockets and threads.

7 min read • View on GitHub • More from RickCarlino

An editorial engraving of a wide theatrical stage seen from the audience. The set is a cozy text-adventure room with a wooden door, a lantern, and a signpost. The back wall is cut away to reveal clockwork gears, each stamped with a small command word, and a single pivoting pointer arm resting near one gear. The image shows the illusion of the game on the front of the stage and the state machine machinery behind it, illustrating that the visible adventure is a thin costume over a switching mechanism.
The costume is the adventure. The machinery is a state machine, and one pointer arm is the session's single active controller.
Key Takeaways

There is a naming trap worth clearing up first. This is not Lattice's MUD, the framework for on-chain Ethereum applications. This is RickCarlino/mud, a Ruby microframework for Telnet text adventures, published as the ruby-mud gem. The two share a name and nothing else.

The Ruby one is small enough to read on a lunch break, and that is the point. Its README claims "0 external runtime dependencies (pure Ruby, yo.)" and it means it. No event loop, no ORM, no world model, no persistence. Just socket, Thread, and an idea about how a text interface should be structured. That idea turns out to be a state machine.

The state machine hiding in a MUD framework

Most game frameworks start with a world: rooms, objects, entities, a database. Ruby Mud starts with a controller, and a controller is a state. It has an entry action (on_start), a vocabulary of things it responds to (allowed_methods), and transitions between states. That is a finite state machine, and the whole thing fits in about 300 lines.

The trick that makes it work is where the state lives. Each connection is a Session, and the session holds exactly one active controller. The input loop reads that field fresh on every line:

def start
  @input_thread = Thread.new(@connection) do |client|
    while (client_input = client.gets.chomp)
      @controller.get_text client_input
    end
  end
end

Because @controller is dereferenced on each iteration, a transition needs no extra plumbing. It just swaps the object:

def transfer_to(controller_name)
  @session.controller = controller_name.new(@session)
end

Note what transfer_to actually does. It constructs a brand new controller and reassigns the session's pointer. The old state is not mutated; it is discarded. The next line of input lands on the new controller's on_start, which has already fired during construction, so the welcome text arrives before the first command is processed. Menus, login flows, and mini-games all fall out of this one move.

A microframework for building Telnet-based text adventure games using Ruby.

Rick Carlino, Repository author / sole listed contributor · RickCarlino/mud README

The pattern is not unique to games. Any program that walks a user through a sequence of modes, each with its own valid inputs, is a candidate. Ruby Mud just happens to wrap that idea in a wooden door and a lantern.

Commands are methods, and the whitelist is the gate

Here is where the framework gets its personality. When a line arrives, it is split, the head word is lowercased, and the rest becomes params:

def get_text(command)
  command = command.split(' ')
  head    = command.shift
  @params = command.join(' ')
  interpret_command head.to_s.downcase
end

Then the dispatch decision happens. Player input is never send-ed to an arbitrary method. A command runs only if its name appears in allowed_methods:

def interpret_command(head)
  if allowed_methods.include? head
    self.send(head)
  else
    send_error
  end
rescue => error
    send_text 'You just broke something. Please tell the admins about this.'
    send_text error.message
end

That array is not a constant. It is a method, so each controller computes its own list, and subclasses extend the base set with super. The default list is just ['quit'], which means every controller can disconnect unless it deliberately replaces the list. A derived controller might read super + ['time', 'say'], building on what the parent already allowed.

This is the security model, and it is elegant and fragile in the same breath. A method that is public but unlisted is unreachable from the socket, which is a real barrier. But the barrier is only as good as the list. Whitelist something like send_text and you have handed a player a way to write arbitrary text to their own connection. The whitelist is the whole defense, so it has to be right.

The composition has a quieter trap. Forget super and you silently drop quit from the list. The player is now stuck in a controller with no exit, and nothing warns you. The tutorial catches this and adds quit back by hand, which is a good instinct and also a hint that the pattern asks a lot of the person writing it.

Click a command to watch it travel through the session and hit the gate. Toggle a chip to see exactly what the whitelist is protecting.

What a whole server looks like in 40 lines

The networking layer is as spare as the controller layer. MudServer.new defaults to 0.0.0.0:4000, which binds every interface. Startup opens a TCP socket and runs an accept loop on a background thread:

def start
  @tcp_socket = TCPServer.new @ip , @port
  @connection_acceptor = Thread.new do
    while connection = @tcp_socket.accept
      @connection_pool << MudServer::Session.new(connection)
    end
  end
  return true
end

Each accepted connection becomes a Session, and each session spawns its own input thread. Concurrency is Ruby threads under the GVL, not an event loop, which is a deliberate simplicity trade: fewer moving parts, and a hard ceiling on how many simultaneous players a single process can comfortably hold.

There is a require-order subtlety worth knowing if you extend it. ruby_mud.rb loads mud_server before the files that reopen class MudServer::..., and it loads abstract_controller before default_controller, because the latter inherits from the former. Get the order wrong and you get a load-time error, not a runtime one. The default controller is a smoke test: connect and it greets you with "It works! Type `quit` to end".

Where the smallness starts to cost

None of the following is a takedown. It is the natural boundary of a proof of concept, and the boundary is interesting because it is drawn in exactly the place a real game would need first.

An editorial engraving close-up of a gatekeeper's hands at a rope barrier. One hand holds a clipboard with a short handwritten list of word-entries, one of which is being added. The other hand is raised palm out, stopping a stream of small paper slips each bearing a single word. One slip has already passed and sits on a tray marked with a checkmark, while a single loose slip has fallen to the floor. The image illustrates how a whitelist gate admits only listed commands and rejects the rest.
The clipboard is <code>allowed_methods</code>. The slips are commands. Whatever is not on the list bounces, and that bounce is <code>send_error</code>.
ConcernStatus
Error handlingPartial: dispatch rescues, session and server do not
Resource managementWeak: sessions never pruned, threads never joined
BroadcastAbsent: no shared world state between connections
ShutdownTest-oriented: closes the listener, not the clients

The README is aware of at least part of this. It is blunt about the transport in a way hobby projects rarely are, and that honesty is worth more than a feature list.

Telnet is insecure by default. All network traffic to the game is sent in the clear. Advise users against using real passwords when running this codebase. This ain't SSH!

Rick Carlino, Repository author / sole listed contributor · RickCarlino/mud README

Ruby Mud vs. the MUD frameworks

It helps to place this against the alternatives, because the comparison makes the niche concrete. Evennia, Ranvier, and CoffeeMUD are game engines. Ruby Mud is a server skeleton with a state abstraction. That is a different product category wearing the same genre label.

ProjectLanguageRuntime depsScopeMulti-user statePersistence
Ruby MudRubyZero (socket + Thread)Microframework: server + controller statesNo (multi-connection only)No
EvenniaPythonYesFull game toolkitYesYes
RanvierNode.jsYesMUD frameworkYesYes
CoffeeMUDJavaYesFull MUD serverYesYes
sourcerer-io/lotsRubyn/aA specific gamen/an/a

Ruby Mud is the only one of these that fits in your head in one sitting. That is the whole point and the whole limitation. You get a working TCP server, a clean state machine, and permission composition for free. Everything a game actually needs on top of that, from persistence to player interaction to graceful shutdown, is yours to write.

If you want a game, pick an engine. If you want to understand how a networked text interface can be built from almost nothing, read this one. It is a finished proof of concept, versioned 0.0.4, solo-built, and it does exactly what it says.