Skip to content
mispy Notes from a night desk

Ruby bindings for the libtcod roguelike library

Roguelikes need a small set of hard things done well: field of view, pathfinding, and a grid that can be drawn quickly. libtcod does those things.

libtcod is a toolkit for roguelike games. It handles the parts that are tedious to write from scratch: field of view, pathfinding, a console grid, and the small conveniences that make a dungeon feel like a place. It is written in C and has bindings for several languages. I wanted one for Ruby.

The first decision was how much of the C interface to expose. A thin binding is easy to generate and hard to use. A thick binding is pleasant and quickly becomes an opinionated framework. I chose a middle path: keep the C functions available with predictable names, then add a small set of Ruby classes for the common workflows.

Say the name twice

C libraries often use a prefix to avoid collisions. A binding can preserve that prefix or strip it. Preserving it makes the mapping obvious: the Ruby method has the same name as the C function, minus the shared prefix. Stripping it makes the code shorter but can create surprises when a new function arrives with a name that is already taken.

I kept a mechanical mapping and wrote it down. Predictability is worth more than brevity in a binding, because the person reading the Ruby is often also reading the C documentation. When the two names line up, the documentation does the work for you.

Who owns the memory

The hardest part of any C binding is not the function call. It is the lifetime of the objects behind the call. A texture created in C must be freed. A map allocated by the library must be released in the right order. A pointer returned by a function may be borrowed or owned, and the difference matters when the garbage collector eventually notices.

Rule of thumb

If the Ruby object did not create the resource, do not let the Ruby object destroy it without an explicit contract.

I wrapped the most common resources in classes with clear constructors and cleanup. For the rest, the raw functions remain available with a warning in the documentation. A binding is a tool, not a guardian. It should make the safe path easy without pretending the unsafe path does not exist.

Platforms are part of the interface

The library ships as a shared object on Linux, a dynamic library on macOS, and a DLL on Windows. The binding has to find the right one or explain clearly why it cannot. A helpful error at load time saves hours of confusion later. This is unglamorous work, but it is the difference between a library that feels native and one that feels broken.

The result is a small bridge between two worlds: a language that makes programmers happy and a toolkit that makes dungeons possible. If you are building a roguelike in Ruby, the grid is now a little closer.