Under the hood

Getting started

A guide to having it running in five minutes. You don't need to know assembly, or to have ever touched an MSX in your life.

1. What you need to install

Four things. On macOS, with Homebrew:

brew install z80dasm openmsx

pasmo isn't in Homebrew; it builds in a couple of minutes:

git clone https://github.com/nataliapc/pasmo.git /tmp/pasmo
cd /tmp/pasmo && ./configure && make && sudo make install

Python 3 already comes with the system. On Linux, the three of them are in the usual repositories (apt install z80dasm pasmo openmsx or equivalent).

Program What it's for
z80dasm Turns the game's bytes into instructions
pasmo Goes the other way round, to check we haven't got it wrong
openmsx MSX emulator. It's there to verify things, not just to play
Python 3 All the project's tools

openmsx is optional if you only want to read the code, but it's what lets you really check the claims instead of just taking them on trust.

2. Get the tape

You need an image of the original tape in TSX format. It isn't distributed here. You can look for it in the usual MSX preservation archives; the canonical name is:

Temptations (1988)(Topo Soft)(ES)[!][RUN'CAS-'][v0.8b].tsx

Leave it in the project folder, next to the Makefile. There's no need to rename it.

3. Run it

make

And that's it. That does four things in a row:

  1. Opens the tape and pulls out the five blocks it contains
  2. Works out which of their bytes are instructions and which are data
  3. Generates the commented listings in src/
  4. Checks that everything adds up

If it finishes with TODO VERDE (all green), it worked.

4. Read it

Open src/temptations_game.asm. That's the main game, about 6,578 lines. Start at the beginning: the first routine is the boot code, and from there you can follow the thread.

A snippet, so you can see what it looks like:

PINTA_MARCADOR:         ; Redibuja el marcador (vidas / pantalla / nivel)
    ld hl,05fc0h        ; Plantilla del marcador -> VRAM 0x1A00, las filas 16..23
    ld de,01a00h
    ld bc,00100h
    call 0005ch         ; BIOS LDIRVM - copia un bloque de memoria a la VRAM
    ld a,(08f12h)       ; A = numero de vidas
    cp 009h             ; El marcador solo tiene un digito: mas de 9 se ven como 9
    jp m,L_86AE
    ld a,009h
L_86AE:
    ld b,05ch           ; 0x5C es el codigo del digito '0' en la fuente del juego...
    add a,b             ; ...asi que 0x5C+vidas da directamente el caracter
    ld hl,01a68h        ; Casilla del digito de VIDAS en la VRAM

If you get lost, THE-CODE.md has the map of where everything is.

How the data blocks are laid out

Every data range declared in the notes comes out as a block of its own: its own heading saying what it is for, its own label, and the dump aligned to its first byte, so where one table ends and the next begins is visible at a glance. An optional line gives the block the row width of its real structure, and that is what makes the twenty-nine screen maps readable: 32 bytes per row is one row of the map, so the walls and the platforms can be seen in the listing itself. The font, the colour table and the sprites go eight bytes per row -one pattern- and the jump tables come out as defw with the destination named next to them.

5. Adding your own comments

Don't edit the .asm files: they're regenerated every time and you'd lose the work. Comments go in ../src/game.notes, anchored to the memory address:

L 0x8698 PINTA_MARCADOR   Redibuja el marcador completo
C 0x86A4 A = numero de vidas
B 0x8698 Este texto sale como cabecera antes de la rutina
D 0x9000 0xCA00 mapas   Los 29 mapas de pantalla, 512 bytes cada uno

Four kinds of line: L gives a routine a name, C adds a comment at the end of an instruction, B puts a block of text before it, and D describes a range of data.

Then make, and it's in the listing.

Other commands

make verify   # same as `make`: rebuilds if needed, then checks
make sanity   # just the fake-coverage check
make clean    # deletes what was generated

To see the game's screens drawn straight from the binary:

python3 tools/render_maps.py dump/turbo2_ram.bin docs/mapas

To play from the emulator, with the original tape:

TEMPT_TSX="$PWD/tu-cinta.tsx" openmsx -machine Philips_VG_8020-20 \
  -script tools/omsx_demo.tcl

(Loading really does take seven minutes, just like in 1988. That script speeds it up ×10 and goes back to normal speed when the game starts.)

If something goes wrong

make: z80dasm: command not found — the tools from step 1 haven't been installed.

no es TZX/TSX ("not a TZX/TSX") — the tape file isn't a valid TSX, or it's compressed. Uncompress it.

openMSX doesn't start, or complains about ROMs — the emulator needs the ROM of a real MSX machine. The project uses a Philips VG-8020 (an MSX1 with 64 KB, which is what the game asks for). Without system ROMs, openMSX only ships C-BIOS, which has no BASIC and therefore can't load tapes.

DIFIERE ("differs") when verifying — something has broken in the annotations. The message says which bytes don't match. If you've just edited the .notes, undo the last change.

The tape

How Temptations loads from a cassette, and why it takes seven minutes.

What is inside the file

The TSX format is the MSX version of TZX, a preservation format that does not store audio but the description of the pulses that were on the tape, plus metadata. That makes it much smaller and much more exact than a WAV.

Our file has 12 blocks:

  Contents
3 blocks Metadata: who dumped it, the load command, the TOSEC name
1 block Game record: title, publisher, year, language
6 blocks The first three programs, in header + data pairs
2 blocks The two big blocks, in turbo format

Blocks of type KCS (0x4B, the MSX's own extension) carry the bytes already demodulated. So there is no audio to decode: the extraction is exact, with no margin for error.

The five blocks

Name Loads at Runs at Size What it is
TEMPT — — 256 B BASIC loader
TOPO 0x9470 0x9470 4,254 B The Topo Soft logo
SLOTS 0xC350 0xC58F 700 B RAM finder + turbo loader
(turbo 1) 0x88B8 0x88B8 12,388 B The title screen
(turbo 2) 0x4000 0x8000 40,449 B The game

The BASIC loader is disarmingly simple:

10 COLOR 1,1,1:SCREEN 2
20 BLOAD"cas:",R
30 BLOAD"cas:",R

It sets the display to black on black (so you do not see the mess while it loads), switches to graphics mode, and loads the next two programs, running them.

SLOTS: the interesting piece

SLOTS does two jobs, and both of them have their charm.

Finding the RAM

The game needs the MSX's full 64 KB. But on an MSX the memory is spread across slots, and every machine organises them its own way. So SLOTS walks through all of them, writing and reading back to work out where there is real RAM:

SONDEA_PAGINA:
    ld a,080h       ; marca de slot expandido
    ld c,004h       ; 4 slots primarios
    ...
    ld (hl),020h    ; escribe 0x20 y lo relee
    ld a,(hl)
    cp 020h
    jr nz,siguiente
    ld (hl),0fah    ; y luego 0xFA, para descartar ROM

And here comes the nice detail: probing the first page of memory is a chicken-and-egg problem. That page is where the BIOS lives, and the routine you need in order to switch slots is in the BIOS. If you switch it out to test the RAM, you are left without the routine.

Topo's solution: copy the routine into itself. SLOTS copies its own version of that function into high memory, rewrites on the fly the destination of its own CALL instruction so that it points at the copy, and only then can it probe page 0 without depending on the BIOS.

    ld hl,00024h        ; primero, la de la BIOS
    ld (0c3b3h),hl      ; escrita como operando del CALL de 0xC3B2
    ...
    ld hl,lc418h        ; ahora copia la nuestra a RAM
    ld de,09c40h
    ld bc,000c8h
    ldir
    ld hl,09c40h
    ld (0c3b3h),hl      ; y reescribe el CALL para usarla

Reading the tape the raw way

The second half is a turbo loader: it reads the tape much faster than the system routines do, measuring the width of the pulses by hand.

It reads bit 7 of register 14 of the sound chip, which is where the MSX hooks up the cassette input, and counts how long it takes to change level. Short pulse, one bit; long pulse, the other.

And while it is at it, this detail:

    ld a,r          ; el registro R del Z80: un valor practicamente aleatorio
    and 00fh
    out (099h),a    ; ...escrito en el registro de color del video

The Z80's R register increments on its own with every instruction. Taking it and dumping it into the backdrop colour produces the coloured stripes you see while it loads. It is not decoration that somebody added: it is a by-product of the read loop itself, for free.

Turbo block format

Each turbo block is:

[ 0x00 ] [ ......data...... ] [ checksum ]

A sync byte, the data, and a check byte worked out so that the XOR of the whole block comes out zero.

This was verified by comparing the memory the emulator had loaded after reading the tape against the bytes in the TSX file: identical, with the one-byte offset that corresponds to the sync byte.

The full sequence

Timed in the emulator, in real machine time:

Moment What happens
0 s The tape starts
65 s The Topo Soft logo appears
96 s SLOTS starts up: it finds the RAM and takes over the loading
181 s The title screen is in; it gets drawn on the display
406 s The game starts

Almost seven minutes. That is how it was.

Rebuilding the tape

The project can go the other way round: take the commented listings, assemble them, and put the whole tape back together with its headers, sync bytes and checksums.

python3 tools/build_tape.py build build/Temptations_rebuild.tsx

The result is byte-for-byte identical to the original TSX, and it loads in the emulator with the same timings. That is the proof that the format is understood all the way through: nothing is left uninterpreted.

The code

A map of where everything lives. For the full listing of routines and data, see INVENTARIO.txt.

Memory map

With the game running, the MSX looks like this:

0x0000 ┌──────────────────────────┐
       │  BASIC ROM               │  NOT touched: the game keeps calling
       │                          │  the BIOS (drawing on screen, reading
0x4000 ├──────────────────────────┤  the joystick, moving blocks of memory)
       │  Graphics                │  font, colours, sprites
0x5C00 │  Menu screen             │
0x5FC0 │  Status bar              │
0x60C0 │  Animation and physics   │  50 slots of 128 bytes
0x79C0 │  Hidden spots            │  per screen
0x7BA0 │  Enemies                 │  per screen
0x7D80 │  Current map buffer      │  512 bytes
0x8000 ├──────────────────────────┤
       │  GAME CODE               │  ~5 KB
0x8F00 │  Variables               │
0x8FA0 │  Four hidden points      │  16 bytes, current screen
0x8FB0 │  Stack                   │  grows downwards from 0x8FFF
0x9000 ├──────────────────────────┤
       │  29 screen maps          │  512 bytes each
0xCA00 ├──────────────────────────┤
       │  (dead code)             │  leftovers from another build
0xD000 ├──────────────────────────┤
       │  Sound player            │
0xD760 │  Menu music              │
0xDB00 │  Per-frame routine       │
0xDE01 └──────────────────────────┘

Leaving the BASIC ROM in place is a design decision: the game leans on the system routines for the common jobs instead of reimplementing them, and in exchange it gives up 16 KB of memory.

The main loop

The whole game fits in this:

BUCLE_PARTIDA:
    call CHK_ABANDONAR         ; ¿han pulsado CTRL+STOP?
    halt                ; espera al barrido de pantalla
    call SFX_FRAME         ; efectos de sonido (motor PSG)
    halt
    call SFX_FRAME
    call DISPARA
    call MUEVE_DISPAROS
    call MUEVE_ENEMIGOS
    call COMPRUEBA_COLISION_SPRITES
    ...
    call MUEVE_JUGADOR
    call COLISIONES_MAPA
    jp BUCLE_PARTIDA

Two halts per loop means the game runs at 25 or 30 frames per second, half the display refresh rate. It is deliberate: it leaves enough time to move everything without any visible stutter.

How the monk moves

The joystick is translated into an action code through a table, and that code is at once the animation index and the character's state:

Joystick direction Code What it does
centre, down, down±diagonal 0x00 idle (there is no crouching)
right 0x01 walk right
left 0x02 walk left
up 0x08 vertical jump
up + right 0x09 jump right
up + left 0x0A jump left

Look at the numbers: bit 3 means "I am jumping" and bits 0 and 1 are the direction. 0x09 is 0x08 | 0x01. It is designed so each thing can be checked separately with a mask.

The animation and physics table

This is the neatest thing in the game. At 0x60C0 there are 50 slots of 128 bytes. Each slot is a sequence of frames, and each frame takes 4 bytes:

byte 0:  X displacement (signed)
byte 1:  Y displacement (signed)
byte 2:  pattern number
byte 3:  the sprite's two colours, one in each half of the byte

A 0x80 in the first byte marks the end of the sequence.

The interesting part is that movement and drawing are the same table. Gravity is not a formula: it is a sequence of frames whose Y displacements keep growing. Neither is the jump: it is another sequence. Changing how the character moves means changing a few bytes of data, not touching code.

Slots 0 to 13 are the monk, and 16 to 48 the enemies, in pairs: slot N and slot N+17 are the same critter facing the other way. To turn an enemy around, the game adds or subtracts 17 from the slot number.

There is even a slot (number 14) whose displacements trace a full circle: it is the enemy that orbits.

The screens

Each screen is a 512-byte block starting at 0x9000: 32 columns × 16 rows, one tile byte per cell, uncompressed. The arithmetic is straightforward:

CARGA_MAPA:
    ld a,(08f0dh)   ; número de pantalla
    ld d,a
    sla d           ; DE = pantalla * 512
    ld e,000h
    ld hl,09000h
    add hl,de
    ld de,07d80h    ; al buffer de trabajo
    ld bc,00200h
    ldir

There are 29 of them: the 28 playable ones plus the victory screen.

The type of each cell is not stored in the map: it is worked out from the tile number. CLASIFICA_TILE sorts them into nine classes (air, wall, extra life, ammo, weapon, deadly ground…) by comparing ranges.

A curious case is class 1: a tile with a blank pattern that the player walks through without noticing, but which makes enemies turn around. They are invisible walls to fence in where each critter patrols. There are 406 of them spread across the 28 maps.

The hidden objects

Each screen also has a list of up to four hidden spots, at 0x79C0 + screen*16, with four bytes per spot:

column, row, shots it takes, prize it drops

The shot counter is stored as a negative: the game increments it until it overflows to zero. Same as enemy stamina.

The striking part, already covered in THE-GAME.md, is that the system works by coordinates: it does not look at what is drawn there. That is why 13 of the game's 30 spots are invisible.

The sound player

A three-channel engine with its own tracker-style format. The data is a byte sequence where values below 0x80 are notes and 0x80 upwards are commands:

Command What it does
0x80 channel volume
0x81 mixer (tone, noise or both)
0x82 back to the start (loop)
0x83 note duration
0x84 rest
0x85 tempo
0x86 compound duration
0x87 load instrument
0x88 noise period
0x89 noise envelope
0x8A repeat envelopes
0x8B end of channel
0x8C call a phrase
0x8D return from phrase (closes the 0x8C)
0x8E channel transposition in semitones

With reusable instruments and calls to phrases, so as not to repeat data. All of it in a little over a kilobyte, and running inside the display interrupt without stealing time from the game.

The variables

They all sit together, from 0x8F00 to 0x8F9F. The main ones:

Address What it is
0x8F09 / 0x8F0A player X and Y, in pixels
0x8F0B current state / animation
0x8F0C frame within the animation
0x8F0D screen (0–28)
0x8F0E level (0–3)
0x8F11 float mode: wings or level 4
0x8F12 lives
0x8F13 / 0x8F14 where to reappear after dying
0x8F17 ammo
0x8F18 weapon
0x8F1E the cheater flag that nobody ever turns on
0x8F20 the 4 active enemies, 5 bytes each
0x8F80 the 7 shots in flight, 4 bytes each

The font

The game does not use ASCII. It has its own table:

space    0x00        (not 0x20)
A..Z     0x41..0x5A  (same as ASCII)
0..9     0x5C..0x65  (shifted)
"        0x68
.        0x6A
,        0x6B
:        0x6C
-        0x6D

That is why the status bar routine does add 0x5C to turn a number into its digit.

And a quirk: the codes for U and V draw the same glyph, so the stored texts say things like "PVES" or "NUEUO" (for "PUES" and "NUEVO") and read perfectly fine on screen.

How it was done, and why you can trust it

A disassembly is easy to get wrong. Read some graphics as if they were instructions and you get pages of invented code that looks perfectly real. It happened to us: an automatic detector flagged leftovers from another build as game code, a quick eyeball said they looked right, and it had to be undone once we found nothing ever calls them.

That's why the project leans on four automatic checks:

Check What it catches
Tests 36 of them, including a set that verifies the docs aren't lying
Reproducibility That the source rebuilds the original binary byte for byte
Trace sanity That graphics weren't marked as code — the check above misses this
Byte budget That not a single byte is left unaccounted for

And on something more important: much of what's claimed here wasn't deduced by reading but by watching the game run. Using the openMSX emulator we set watchpoints on memory to see which code touched what, sampled the processor during play to know what actually executes, and captured the real display to check it against what the code says.

That's how the lives counter was identified, for instance: not by deduction, but by confirming that a single routine reads it and that this routine writes the result into the exact status-bar cell where the number appears.