🎮 Why test an NES game?
During Hack Week 26 I wrote Hack to the Future, an endless runner for the Nintendo Entertainment System, in C. A 1983 console has no debugger you can attach to, no printf, and no unit test framework. What it has is an emulator: Mesen2 embeds a Lua scripting engine and a headless --testRunner mode, so a script can run the ROM, press buttons, read RAM, VRAM and sprite memory, and exit with a status code. That is everything a test needs.
The game ended up with about ten Lua test files, and they saved me many times (a drone that never hit a standing player, a HUD that scrolled with the playfield…). In this series I will rebuild the idea from scratch, in the smallest possible program, following the classic red-green-refactor loop:
- 🔴 write a test, watch it fail
- 🟢 write the least code that makes it pass
- 🔵 clean up, with the tests as safety net
Goal of the series: a sprite you can move with the d-pad. Tiny, but it touches video, memory and input. Today: the toolbox, the blank project, and the first failing test.
🕹️ What the NES gives you (and how it was in 1985)
The numbers are the reason testing matters. The NES (Famicom in Japan) is built around a Ricoh 2A03, a 6502 derivative at about 1.79 MHz, plus a separate video chip, the PPU. That is the whole budget:
- 2 KB of RAM for the CPU, and another 2 KB of video RAM. Not 2 MB: kilobytes
- a 6502 with 3 registers: an 8-bit accumulator and two 8-bit index registers. No multiply, no divide, no floating point; a C
intis a luxury - ~30,000 CPU cycles per frame. Everything the game does in one 1/60 s tick has to fit, or the game slows down
- the PPU can only be written safely during vblank, the short pause between frames (about 2,270 cycles). Touch it at the wrong moment and the screen glitches
- 64 sprites, at most 8 per scanline; the ninth is not drawn. Classic games live with this by flickering on purpose, rotating which sprites they submit on each frame
- 256x240 pixels, 25 colours at a time out of a fixed palette of about 54, with attributes that colour whole 16x16 pixel blocks
- 32 KB of code and 8 KB of graphics on the simplest cartridge. Bigger games shipped a mapper chip on the cartridge to switch memory banks at runtime (my game uses the MMC3 one)
Back then, nearly everything was written by hand in 6502 assembly. There was no printf, and the .nes files you run today in an emulator did not exist: studios used expensive development kits, burned EPROMs to try the game on a real console, and debugged with in-circuit emulators and a lot of patience. A bug in a frame-timing routine could show up only on one particular scanline. A test suite? You would have needed a second console and a very understanding colleague.
We are lucky. An emulator is a console you can script: it can run a frame, stop, and let you read the exact bytes the PPU would draw. That is what makes test-driven development on this hardware possible today, with a modern C compiler on top.
🧰 The toolbox
- llvm-mos: a modern LLVM-based C compiler for the 6502. Its SDK ships
neslibandnesdoug, the popular C libraries for NES programming. This part usesneslib;nesdougjoins in part 2 - a Tumbleweed container, so no development tools are installed on the host
- Mesen2, installed on the host: the emulator that runs the tests. Pin the version you use and write it down: the Lua API and
--testRunnerare part of your test harness, and they do change between releases make,podman
All the code is in nes-tdd-demo, one branch per part: this part is branch part-1. Check it out with git clone -b part-1 https://github.com/ilmanzo/nes-tdd-demo and follow along.
🐳 The container
The compiler lives in a container, pinned by version and checksum:
FROM registry.opensuse.org/opensuse/tumbleweed
ARG LLVM_MOS_VERSION=v23.3.0
ARG LLVM_MOS_SHA256=9f694497bc93a7c876d8c62325c7d74e7860346d80fbcd0555e19ba6856658c8
RUN zypper --non-interactive install --no-recommends make tar xz curl libstdc++6 \
&& zypper clean -a \
&& curl -fsSL -o /tmp/llvm-mos.tar.xz \
https://github.com/llvm-mos/llvm-mos-sdk/releases/download/${LLVM_MOS_VERSION}/llvm-mos-linux.tar.xz \
&& echo "${LLVM_MOS_SHA256} /tmp/llvm-mos.tar.xz" | sha256sum -c - \
&& mkdir /opt/llvm-mos \
&& tar -xJf /tmp/llvm-mos.tar.xz -C /opt/llvm-mos --strip-components=1 \
&& rm /tmp/llvm-mos.tar.xz
ENV PATH=/opt/llvm-mos/bin:$PATH
WORKDIR /src
make podman builds the image and runs make inside it, with the project directory mounted (and the ROM owned by you, thanks to --userns=keep-id):
CC = mos-nes-nrom-clang
CFLAGS = -Oz -flto -ffunction-sections -fdata-sections -Isrc
LDFLAGS = -flto -Wl,--gc-sections -Wl,--print-memory-usage -lneslib -lnesdoug
TARGET = nes-tdd-demo.nes
SRCS = src/main.c
HEADERS = $(wildcard src/*.h)
TESTS = tests/hello.lua
$(TARGET): $(SRCS) $(HEADERS)
$(CC) $(CFLAGS) $(SRCS) -o $(TARGET) $(LDFLAGS)
podman:
podman build -t llvm-mos-demo -f Containerfile .
podman run --rm --userns=keep-id -v "$(CURDIR)":/src:Z llvm-mos-demo make
.PHONY: podman test
mos-nes-nrom-clang targets the simplest cartridge layout, NROM: 32 KB of code, 8 KB of graphics, no bank switching. Besides the ROM, the linker writes a label file (nes-tdd-demo.mlb) that maps every C variable to its RAM address. Remember it, we will need it when tests have to look at variables by name.
🧱 The blank project
The program that makes the first commit: it boots, sets a palette, switches the video on, and then waits for the next frame, forever. It draws nothing.
#include <neslib.h>
static const unsigned char palette[16] = {
0x0f, 0x00, 0x10, 0x30,
0x0f, 0x01, 0x11, 0x31,
0x0f, 0x06, 0x16, 0x26,
0x0f, 0x09, 0x19, 0x29
};
int main(void) {
pal_bg(palette);
ppu_on_all();
while (1) {
ppu_wait_nmi();
}
return 0;
}
$ make podman
...
prg_rom: 32 KB 32 KB 100.00%
ram: 32 B 1536 B 2.08%
[SUCCESS] Built nes-tdd-demo.nes for NES NROM
It compiles. On the emulator it shows a black screen:

🧪 Test first
How can a Lua script see “the screen”? The NES has no framebuffer: the picture is built by the PPU (the video chip) from tiles. A 32x30 grid called nametable says which tile goes where, and Mesen exposes the PPU memory to scripts. If we write text with a font where the tile number equals the ASCII code, “HELLO” on screen means the bytes 48 45 4C 4C 4F in the nametable. That font does not exist yet: part 1 writes no tile at all, so the check below cannot pass until part 2 draws the greeting. Which is exactly the point. The helper to read the nametable:
local NT_BASE, NT_COLS = 0x2000, 32
T.PPU = emu.memType.nesPpuMemory -- pattern tables at $0000, nametable A at $2000
function T.nt_text(col, row, len)
local c = {}
for i = 0, len - 1 do
c[#c + 1] = string.char(emu.read(NT_BASE + row * NT_COLS + col + i, T.PPU))
end
return table.concat(c)
end
The rest of the harness, tests/lib.lua (about 110 lines), has a few more helpers: T.wait(n) to let n frames pass, T.press(buttons, n) to hold the d-pad, T.check to count failures, T.shot to take a screenshot and T.run that drives the test as a coroutine, one step per video frame, with a watchdog. It exits with status 0 if all checks passed, 1 if one failed, 2 on a script error. That exit code is what make and your CI will see.
Now the test. Our “feature” is: the game greets the player. After ten frames, “HELLO” must be on screen at column 12, row 14:
local T = dofile((os.getenv("ROOT") or ".") .. "/tests/lib.lua")
local function printable(s)
return (s:gsub("[^ -~]", function(c)
return string.format("\\x%02x", c:byte())
end))
end
T.run(function()
T.wait(10)
local COL, ROW = 12, 14
local got = T.nt_text(COL, ROW, 5)
local msg = string.format('nametable row %d col %d: expected "HELLO", got "%s"', ROW, COL, printable(got))
T.check(got == "HELLO", msg)
T.shot("hello")
end, 60)
make test runs it with the headless emulator:
MESEN ?= $(HOME)/.local/opt/mesen2/Mesen
MESEN_PRELOAD ?= /usr/lib64/libstdc++.so.6
test:
@test -n "$(TESTS)" || { echo "TESTS is empty: no test would run"; exit 2; }
@test -f $(TARGET) || { echo "build $(TARGET) first"; exit 1; }
@! find src -type f -newer $(TARGET) | grep -q . || { echo "$(TARGET) is older than its sources: rebuild (make podman)"; exit 1; }
mkdir -p tests/out
@for t in $(TESTS); do \
echo "== $$t"; \
ROOT=$(CURDIR) LD_PRELOAD=$(MESEN_PRELOAD) timeout 300 $(MESEN) --testRunner \
--nes.port1.type=NesController --debug.scriptWindow.allowIoOsAccess=true \
$(TARGET) $$t; rc=$$?; \
if [ $$rc -eq 1 ]; then echo "RED: $$t has failing checks"; exit 1; \
elif [ $$rc -ne 0 ]; then echo "BROKEN: $$t (runner exit $$rc), not a red"; exit 2; fi; \
done
A few flags deserve an explanation: --nes.port1.type=NesController plugs a standard controller in port 1 (we will need it in part 3), allowIoOsAccess lets the script read the label file and write screenshots, ROOT tells the script where the project is (the emulator’s working directory is not ours). Mesen2’s own help lists the script before the ROM, --testRunner [lua script] [rom file], but positional arguments are sorted by extension, so either order works.
LD_PRELOAD works around a std::bad_cast abort inside MesenCore.so with the system libstdc++ I hit on openSUSE: drop it if your distribution’s library is fine, and a static build will not need it at all.
The Makefile also refuses to run if a source file is newer than the ROM: a test against a stale ROM is worse than no test. The first guard is worth a line: with TESTS empty the loop would run zero times and make would exit 0, a green suite with no tests in it.
🔴 RED
A little vocabulary, used in the whole series. A check is one assertion; a test is one Lua file; the suite is all the tests, run by make test. The suite is red when a check fails, green when they all pass, and broken when it cannot reach a verdict (build error, missing ROM, runner crash, timeout). Broken is not red: a typo in a test must never pass for a successful first step, so the Makefile prints RED or BROKEN and exits with different codes. One exception to declare: the watchdog inside T.run fires a failing check when a test hangs, so an infinite loop in the game shows up as red, not broken.
Time to run it:
$ make podman && make test
mkdir -p tests/out
== tests/hello.lua
FAIL nametable row 14 col 12: expected "HELLO", got "\x00\x00\x00\x00\x00"
1 check, 1 failed
1 FAILED
RED: tests/hello.lua has failing checks
make: *** [Makefile:47: test] Error 1
Red. The failure is exactly the one we expect: the nametable is full of zeros, nobody wrote the greeting. Two details matter here:
- the test fails for the right reason. A test that has never failed proves nothing; one that fails because of a typo in the test itself proves even less. I checked with a throwaway patch that writing “HELLO” with
vram_adr+vram_writeflips the test to green, then threw it away - the failure message says what was expected and what was found. When this runs in CI at 3 AM, that line is all you will have
📚 Credits & further reading
- the NESdev wiki is the reference for everything above: nametables, palettes, OAM and its 8-sprites-per-line limit, NROM
- the Mesen2 Lua API reference documents
emu.read,emu.write,emu.stopand the callbacks the harness is built on - llvm-mos ships
examples/nesin the SDK: small programs that are worth compiling and reading - nesdoug.com and the
neslibheader in the SDK for the C side of NES programming
⏭️ Next
In part 2 we’ll make this test pass with the dumbest code possible, and then write the next failing test: the same greeting at a different position, to get us out of the hard-coded cheat.

