A different kind of computer IV: virtual machines from the seventies

· PM-mirror


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:

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.

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:

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
####...#..####.####.#..#.####.####.####.
#..#..##.....#....#.#..#.#....#.......#.
#..#...#..####.####.####.####.####...#..
#..#...#..#.......#....#....#.#..#..#...
####..###.####.####....#.####.####..#...
........................................
####.####.####.###..####.###..####.####.
#..#.#..#.#..#.#..#.#....#..#.#....#....
####.####.####.###..#....#..#.####.####.
#..#....#.#..#.#..#.#....#..#.#....#....
####.####.#..#.###..####.###..####.#....

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:

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!"

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

What's going on in there:

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:

  1. Weisbecker described the system in BYTE magazine in December 1978, in an article called "An Easy Programming System".

  2. Infocom's compiler, ZILCH, was never released. The games survived because the story files and the interpreters did.

  3. 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."