A different kind of computer IV: virtual machines from the seventies
Long before fantasy consoles, two computers were invented that only ever existed as programs: CHIP-8, built to make games easy on a 1977 kit computer, and the Z-machine, built to carry Zork to every computer on the market. With a CHIP-8 in Python and a look inside Zork.
The fantasy consoles from the second part of this series are computers that were never built. They exist only as programs, and they behave like hardware anyway. The idea sounds modern, but it's almost fifty years old. At the end of the 1970s two of these imaginary machines appeared, for opposite reasons. CHIP-8 was made so that people with a tiny kit computer could write games without learning machine code. The Z-machine was made so that one game could run on every computer on the market.
Both are still alive. People write new CHIP-8 games every year, and Zork, compiled in the 1980s, runs today on a Linux terminal without changing a single byte. This part looks at both, and builds a working CHIP-8 in Python along the way.
CHIP-8: a computer inside a computer #
In 1977 RCA sold the COSMAC VIP, a microcomputer you bought by mail order as a kit for US$275. It had 2 KB of RAM, expandable to 4 KB, a hexadecimal keypad and a video output for a TV. Joseph Weisbecker, the RCA engineer behind its processor, also wrote the thing that made it fun: CHIP-8, a small interpreted language for making games. The VIP shipped with 20 games written in CHIP-8, printed as lists of instructions that you typed in yourself.1
CHIP-8 describes a machine much simpler than the real one underneath:
- Memory: 4 KB. The interpreter itself took the first 512 bytes, which is why every CHIP-8 program starts at address
0x200to this day. - Registers: sixteen 8-bit registers called V0 to VF, plus a 12-bit register called I that points into memory. VF doubles as a flag.
- Screen: 64 by 32 pixels, black and white.
- Keyboard: 16 keys, from 0 to F.
- Timers: two of them, counting down 60 times per second, one for delays and one for sound.
- Instructions: 35, each exactly two bytes long.
With only 35 instructions, all of the same size, the whole machine fits in a few hundred lines of almost any language, and that's why CHIP-8 is the traditional first project for anyone who wants to write an emulator.
It also had a second life. In 1990 Andreas Gustafsson wrote CHIP-48, an interpreter for the HP-48 graphing calculator, and in 1991 Erik Bryntse extended it into SUPER-CHIP, with a bigger screen and new instructions. Today a lot of new CHIP-8 work happens in Octo, an online editor, assembler and emulator by John Earnest, along with XO-CHIP, his extension that adds color and better sound.
A CHIP-8 in fifty lines of Python #
Every emulator, from CHIP-8 to a PlayStation, runs the same loop. It fetches the next instruction from memory, decodes what it means and executes it, and then does it again.
Source
digraph {
rankdir=LR;
node [shape=box, style=rounded, fontname="Helvetica", margin="0.4,0.12"];
edge [fontname="Helvetica"];
fetch [label="fetch\nread 2 bytes at pc"];
decode [label="decode\nsplit into parts"];
execute [label="execute\nchange registers,\nmemory or screen"];
fetch -> decode;
decode -> execute;
execute -> fetch [label="pc += 2"];
}To have something to run, here's a CHIP-8 program assembled by hand for this post. It's 19 instructions, 38 bytes, and it draws the 16 hexadecimal digits in two rows using the font that every CHIP-8 keeps in low memory. One instruction per line:
- 00E0: clear the screen
- 6000, 6100, 6200: set V0 (x), V1 (y) and V2 (the digit) to zero
- F229: point I at the font sprite for the digit in V2
- D015: draw 5 rows of that sprite at (V0, V1)
- 7005, 7201: move x five pixels right, go to the next digit
- 3208, 1208: if the digit isn't 8 yet, jump back to F229
- 6000, 6106: x back to zero, y six pixels down
- F229, D015, 7005, 7201, 3210, 1218: the same loop, until the digit reaches 16
- 1224: jump to itself, which is how CHIP-8 programs usually stop
And this is chip8.py, a CHIP-8 that understands the seven instructions this program uses, plus one more for loading I:
FONT = bytes.fromhex(
"F0909090F0" "2060202070" "F010F080F0" "F010F010F0" "9090F01010"
"F080F010F0" "F080F090F0" "F010204040" "F090F090F0" "F090F010F0"
"F090F09090" "E090E090E0" "F0808080F0" "E0909090E0" "F080F080F0" "F080F08080")
ROM = bytes.fromhex(
"00E0 6000 6100 6200" # clear, x=0, y=0, digit=0
"F229 D015 7005 7201" # point at the digit, draw it, x+=5, digit+=1
"3208 1208" # if digit != 8, go back to F229
"6000 6106" # x=0, y=6 (next row)
"F229 D015 7005 7201" # same as above
"3210 1218" # if digit != 16, go back
"1224") # jump to itself: the program is done
mem = bytearray(4096)
mem[0:len(FONT)] = FONT
mem[0x200:0x200 + len(ROM)] = ROM
V, I, pc = [0] * 16, 0, 0x200
screen = [[0] * 64 for _ in range(32)]
while True:
op = mem[pc] << 8 | mem[pc + 1]
pc += 2
x, y = op >> 8 & 0xF, op >> 4 & 0xF
nnn, nn, n = op & 0xFFF, op & 0xFF, op & 0xF
kind = op >> 12
if op == 0x00E0:
screen = [[0] * 64 for _ in range(32)]
elif kind == 0x1:
if nnn == pc - 2: break
pc = nnn
elif kind == 0x3:
if V[x] == nn: pc += 2
elif kind == 0x6:
V[x] = nn
elif kind == 0x7:
V[x] = (V[x] + nn) & 0xFF
elif kind == 0xA:
I = nnn
elif kind == 0xD:
V[0xF] = 0
for row in range(n):
bits = mem[I + row]
for col in range(8):
if bits >> (7 - col) & 1:
px, py = (V[x] + col) % 64, (V[y] + row) % 32
V[0xF] |= screen[py][px]
screen[py][px] ^= 1
elif kind == 0xF and nn == 0x29:
I = V[x] * 5
else:
raise SystemExit(f"unknown opcode {op:04X}")
for line in screen[:11]:
print("".join("#" if p else "." for p in line[:40]))$ python3 chip8.py ####...#..####.####.#..#.####.####.####. #..#..##.....#....#.#..#.#....#.......#. #..#...#..####.####.####.####.####...#.. #..#...#..#.......#....#....#.#..#..#... ####..###.####.####....#.####.####..#... ........................................ ####.####.####.###..####.###..####.####. #..#.#..#.#..#.#..#.#....#..#.#....#.... ####.####.####.###..#....#..#.####.####. #..#....#.#..#.#..#.#....#..#.#....#.... ####.####.#..#.###..####.###..####.#....
Source
$ python3 chip8.py
####...#..####.####.#..#.####.####.####.
#..#..##.....#....#.#..#.#....#.......#.
#..#...#..####.####.####.####.####...#..
#..#...#..#.......#....#....#.#..#..#...
####..###.####.####....#.####.####..#...
........................................
####.####.####.###..####.###..####.####.
#..#.#..#.#..#.#..#.#....#..#.#....#....
####.####.####.###..#....#..#.####.####.
#..#....#.#..#.#..#.#....#..#.#....#....
####.####.#..#.###..####.###..####.#....That's the top left corner of a 64 by 32 screen, printed with # for lit pixels and . for dark ones. The parts worth understanding:
-
op = mem[pc] << 8 | mem[pc + 1]reads two bytes and glues them into one number. CHIP-8 stores the high byte first, so the order matters: swap them and nothing works. -
pc += 2happens right after the fetch, before anything runs. That's why the skip instruction (3XNN) only needs to add 2 more, and why the program stops by asking whether a jump points at itself,pc - 2. - The instruction is cut into pieces with shifts and masks.
xandyare register numbers,nnnis an address,nnis a byte andnis a small count. Every CHIP-8 instruction uses some of these, so the decoder computes all of them once. -
& 0xFFkeeps the registers inside 8 bits. Without it,7201would count past 255 and Python would happily store 256, which a real CHIP-8 never could. - Drawing is XOR. A sprite flips the pixels it touches, so drawing the same sprite twice erases it, and that's how CHIP-8 games animate. When a lit pixel gets turned off, VF becomes 1, and that one flag is all the collision detection the machine has.
-
I = V[x] * 5works because the font sits at address 0 and every digit is five bytes tall.
The full machine has 35 instructions, and the other 27 follow the same pattern: calls and returns with a small stack, arithmetic between registers, reading the keypad, the two timers and a random number instruction. To test them one at a time, there's the CHIP-8 test suite by Timendus, a set of ROMs that check each instruction and print the result on screen. Once it passes, the screen can move from print to a real window, and the Pyxel engine from part two is a good fit for that, since its loop already calls you 60 times per second.
The Z-machine: one game, every computer #
In May 1977 four people at MIT started a game on a DEC PDP-10 mainframe: Tim Anderson, Marc Blank, Bruce Daniels and Dave Lebling. It was Zork, a text adventure where you type commands like open mailbox and the game answers in prose. In 1979 Anderson, Blank and Lebling, with five other members of their group at MIT, founded a company called Infocom, and Zork became its first product.
The problem was the market. Home computers in 1979 were a mess of incompatible machines, each with its own processor, its own disk format and much less memory than a PDP-10. Rewriting Zork for each of them would have taken forever. So Joel Berez and Marc Blank designed a computer that didn't exist, the Z-machine, and Infocom compiled its games for it. To bring every game to a new computer, they only had to write one program for it: an interpreter for the Z-machine. The game itself, called a story file, stayed the same everywhere.2
The games were written in ZIL, the Zork Implementation Language, a simplified dialect of MDL, which in turn descends from Lisp. Even so, Zork didn't fit in the memory of a home computer, so Lebling split it into separate games. The first part came out as Zork I for the TRS-80 in December 1980, and the rest became Zork II and Zork III. By July 1984 Infocom was publishing for 15 different computers, plus generic CP/M and MS-DOS, all from the same story files.
Infocom made six versions of the Z-machine. Version 3 is the one most of its games use, and the later ones added more memory, more text styles and finally some graphics in version 6.
Playing Zork in 2026 #
In November 2025 Microsoft, which owns what's left of Infocom, released the source code of Zork I, II and III under the MIT license. The Zork I repository has the ZIL files and, in the COMPILED folder, the story file zork1.z3, 86,838 bytes of Z-machine code. Any modern interpreter can play it. On Debian and Ubuntu, apt install frotz brings dfrotz, a version of the Frotz interpreter that works in a plain terminal. Here -m turns off the pauses for more text, -p keeps the output in plain ASCII and -w 72 wraps the lines at 72 columns:
$ dfrotz -m -p -w 72 zork1.z3 Using normal formatting. Loading zork1.z3. ZORK I: The Great Underground Empire Infocom interactive fiction - a fantasy story Copyright (c) 1981, 1982, 1983, 1984, 1985, 1986 Infocom, Inc. All rights reserved. ZORK is a registered trademark of Infocom, Inc. Release 119 / Serial number 880429 West of House You are standing in an open field west of a white house, with a boarded front door. There is a small mailbox here. >open mailbox Opening the small mailbox reveals a leaflet. >read leaflet (Taken) "WELCOME TO ZORK! ZORK is a game of adventure, danger, and low cunning. In it you will explore some of the most amazing territory ever seen by mortals. No computer should be without one!"
Source
$ dfrotz -m -p -w 72 zork1.z3
Using normal formatting.
Loading zork1.z3.
ZORK I: The Great Underground Empire
Infocom interactive fiction - a fantasy story
Copyright (c) 1981, 1982, 1983, 1984, 1985, 1986 Infocom, Inc. All
rights reserved.
ZORK is a registered trademark of Infocom, Inc.
Release 119 / Serial number 880429
West of House
You are standing in an open field west of a white house, with a boarded
front door.
There is a small mailbox here.
>open mailbox
Opening the small mailbox reveals a leaflet.
>read leaflet
(Taken)
"WELCOME TO ZORK!
ZORK is a game of adventure, danger, and low cunning. In it you will
explore some of the most amazing territory ever seen by mortals. No
computer should be without one!"Those bytes were compiled for an imaginary computer decades ago, and they run unchanged on an interpreter written in C for machines that didn't exist back then.
Reading a story file in Python #
A story file is just bytes, and the first 64 of them are a header that describes the rest. This script reads some of it, checks the file the way the Z-machine's own verify instruction does, and then decodes Zork's dictionary, the list of every word the game understands:
import sys
data = open(sys.argv[1], "rb").read()
word = lambda a: data[a] << 8 | data[a + 1]
print("version:", data[0])
print("release:", word(0x02))
print("serial:", data[0x12:0x18].decode())
print("file length:", word(0x1A) * 2, "bytes")
print("starts at:", hex(word(0x06)))
total = sum(data[0x40:word(0x1A) * 2]) & 0xFFFF
print("checksum:", hex(word(0x1C)), "ok" if total == word(0x1C) else "BAD")
A0 = "abcdefghijklmnopqrstuvwxyz"
A2 = " \n0123456789.,!?_#'\"/\\-:()"
def zstring(addr, words):
chars, out, alpha = [], "", A0
for i in range(words):
w = word(addr + 2 * i)
chars += [w >> 10 & 31, w >> 5 & 31, w & 31]
for c in chars:
if c == 5: alpha = A2; continue
if c >= 6: out += alpha[c - 6]
alpha = A0
return out
d = word(0x08)
seps = data[d]
size, count = data[d + seps + 1], word(d + seps + 2)
first = d + seps + 4
words = [zstring(first + i * size, 2) for i in range(count)]
print("dictionary:", count, "words")
print(" ".join(w for w in words if w[0] in "xz"))$ python3 zheader.py zork1.z3 version: 3 release: 119 serial: 880429 file length: 86838 bytes starts at: 0x50d5 checksum: 0xbf44 ok dictionary: 684 words xyzzy z zork zorkmi zzmgck
Source
$ python3 zheader.py zork1.z3
version: 3
release: 119
serial: 880429
file length: 86838 bytes
starts at: 0x50d5
checksum: 0xbf44 ok
dictionary: 684 words
xyzzy z zork zorkmi zzmgckWhat's going on in there:
- The first byte is the version, 3, which is also why the file ends in
.z3. The release and serial match what the game printed when it started. - The file length is stored divided by two, so the script multiplies it back. In version 3 every packed address works this way, which let a 16-bit number reach 128 KB.
- The checksum is the sum of every byte after the header, cut to 16 bits. With it, a player could find out whether a floppy had gone bad.
- Text is compressed. Each 16-bit word holds three 5-bit characters, and the values 6 to 31 are the letters a to z. Character 5 switches to a second alphabet for one character, which is where digits and punctuation live. That's what
zstringundoes. - Every dictionary entry has room for only six of those characters, so
zorkis complete, butzorkmid, the game's currency, is stored aszorkmi. The parser only looks at the first six letters of each word you type, which is whyzorkmidxyzgets the same answer when you examine it.3
After Infocom #
Infocom closed in 1989, and the Z-machine went on without it. In the early 1990s Graham Nelson studied the existing story files closely enough to write down a standard for the machine, and in May 1993 he released Inform, a compiler that produces new Z-machine games. He also defined versions 7 and 8 for bigger stories. In 1995 Stefan Jokisch wrote Frotz for DOS, the interpreter that dfrotz comes from, and it has since been ported to Unix, RISC OS and iOS.
Inform is still around. Inform 6, the direct descendant of that 1993 compiler, still produces Z-machine story files, and Inform 7 lets you write games in something close to English.
Where to start #
For CHIP-8, the quickest path is Octo. It runs in the browser, comes with examples, and its assembly language reads a lot better than the hex above. To understand the machine, writing your own interpreter is the classic route: start from the Python above, add instructions until the test suite passes, then put it in a window.
For the Z-machine, play first. Frotz is in most package managers, and the Zork I repository has a story file ready to run. If you want to write your own interactive fiction, Inform 7 is the modern way. If you're curious about how Infocom worked, ZILF compiles ZIL, the same language as the files in that repository.
Some advice for either machine:
- Keep a hex dump open while you work.
xxd zork1.z3 | headshows the same header bytes the script reads, and seeing the raw numbers makes the code much easier to follow. - Make one instruction work at a time and check it before moving on. A common emulator bug is an instruction that seems to work and quietly sets the wrong register.
- Read other people's interpreters after you write yours, not before. They make much more sense once you've faced the same decisions.
Notes
Weisbecker described the system in BYTE magazine in December 1978, in an article called "An Easy Programming System". ↩
Infocom's compiler, ZILCH, was never released. The games survived because the story files and the interpreters did. ↩
xyzzy is the magic word from Colossal Cave Adventure, the game that inspired Zork. Typing it in Zork only gets you a hollow voice saying "Fool." ↩