Under the hood

Getting started

What you need

pasmo and z80dasm to assemble and disassemble, and Python 3 for the tools. Nothing else.

The cartridge is not distributed with this repository: you need your own copy, named monkey.rom in the project root. It is exactly 16384 bytes with this sha256:

fdf62cfa6db239fcaa3614b56263dd58e8797b206663e491588c062220b16b01

With any other dump the listing will not reassemble. make comprueba tells you in one line.

The commands

make          # trace, generate the listing and check everything
make verify   # assemble the listing and compare its sha256 with the cartridge
make sanity   # what reassembly cannot catch
make test     # the 18 tests on the listing, which do not need the cartridge
make web      # the pictures and these pages

make chains the first four. If all goes well, the line that matters is this one:

  ensamblado : 16384 bytes  fdf62cfa...20b16b01
  original   : 16384 bytes  fdf62cfa...20b16b01
OK: reproducible byte a byte

What is in each folder

   
src/monkey.asm the commented listing, generated; never edited by hand
src/monkey.notes the annotations: labels, comments, headers and data ranges, anchored to addresses
src/monkey.entries the entry points the trace cannot deduce, each with its justification
src/monkey.nocode the zones the tracer must not read as code
tools/ the tracer, the listing generator, the checks and the drawing tools
tests/ 18 tests on the listing and the notes
docs/ this site
work/ what make produces along the way

How to read the listing

Every routine has an uppercase name and a comment saying what it does and what it takes. Data blocks are labelled DATA_<use>, with the width of their structure, and each has an explanation of what it is and how that is known. Addresses are the real ones of the cartridge in page 1: 0x4000-0x7FFF.

To change anything, edit src/monkey.notes and run make again: the listing is regenerated and the checks say whether it still holds.

How it was done

The tracer (tools/z80trace.py) follows the flow from the header's entry point and from what monkey.entries declares: the interrupt and the targets of the two dispatchers, which jump through tables. Whatever is not code is left as a gap, and every gap is closed by finding the instruction that reads it (tools/quien_apunta.py, tools/refs.py) and checking the format the consuming code implies: the two RLE blocks decompress and end exactly on the byte they should, and the tile lists run to their 0xFF.

What cannot be read is measured. tools/graficos.py builds video memory by repeating INIT's copies and the result matches a dump from the emulator sprite by sprite; the equation generator was sampled six hundred times in the emulator to check what the code says about it.

Reproducibility

The cartridge

The header and the machine

The 16384 bytes begin with AB: the BIOS recognises them as a cartridge, maps them into page 1 (0x4000-0x7FFF) and, once the machine has booted, calls the header's entry point, 0x40AF. STATEMENT, DEVICE and TEXT are zero. The five eight-byte stubs after the header (pop hl / ld (0),hl / ret) are used by nobody: filler for the hooks the header leaves empty.

INIT (0x40AF) disables interrupts, writes jp 0x4038 into the H.KEYI hook (0xFD9A), sets the stack at 0xE400, loads video memory, clears the game's RAM, enables interrupts and sits in a two-byte jr $ (0x419B). From then on the whole game runs inside the interrupt, one step per frame. 0xE005 is the lock: if a step takes longer than a frame, the next interrupt plays the music, flushes the sprites and leaves.

Video memory

SCREEN 2 with 16×16 sprites (0x488C: R0=02, R1=A2, R2=0E, R3=7F, R4=07, R5=76, R6=03, R7=E1).

VRAM what
0x0000 tile colours, three identical thirds
0x1800 the patterns of the 64 sprites
0x2000 tile patterns, three identical thirds
0x3800 the name table
0x3B00 the sprite attributes

Tiles 0x00-0xB7 come compressed: patterns at 0x5156 (0x515 bytes) and colours at 0x566B (84 bytes), both with the same RLE (0x6C84: 0 ends; n < 0x80 repeats the next byte n times; n ≥ 0x80 copies n & 0x7F bytes as they are). Decompressed they give 1472 bytes each, exactly 184 tiles, and both blocks end where the next begins. Tiles 0xB8-0xC3 are loaded later by 0x4728 from 0x5EFF: the pieces of the big equation digits that did not fit in the first block, sharing numbers with the title sign, which is drawn into tiles 0xB8-0xFF one pixel row at a time (0x4C77).

The tiles

Of the tiles: 0x00 empty, 0x01-0x04 the card edge, 0x05-0x08 the four platform bars (one per colour), 0x09-0x0C the red arrow, 0x0D-0x14 the panel's monkey faces (normal and crying), 0x15 the flower, 0x16-0x2F the big KONAMI, 0x30-0x5B digits, ©, letters and dash in ASCII, 0x5C-0x5F "key" and "with" in small type, 0x60 blue, 0x61-0x7A the cards with their digits, 0x7B-0xB7 the big digits and signs.

The sprites

INIT copies the first six sprites of 0x56BF to 0x1800, and then the 22 of the same block again from 0x18C0, because COPIA_A_VRAM leaves HL as it was (0x40CF). So VRAM sprite n, for n from 6 to 27, is the cartridge's n − 6: that is why the monkey is at patterns 0x00 and 0x18, and the crab at 0x30. The same 22 are mirrored bit by bit (0x4107) into 0x1CC0: the mirror of sprite k is pattern 0x98 + 4k. Besides, 0x597F (500, 100, banana and grapes) goes to 0x1B80, 0x59FF (the monkey walking left, drawn separately) to 0x1C00 and 0x5ABF (the big face, the apple and the card) to 0x1F80.

The sprites

Every character is two overlaid sprites: the body in one colour and the details in another (the monkey blue and white, the crab red and yellow, the professor dark red and white). And the game swaps whole blocks depending on what the monkey carries: 0x6044 points to three sets —normal, with the fruit on his head (0x5B3F) and with the card held high (0x5BFF)—, and 0x5F80 loads whichever 0xE10E asks for into 0x1800 and 0x1C00. The balloons (0x5E3F) overwrite the 500 at 0x1B80 while the equation rises, and the big face of 0x5E7F overwrites the monkey at 0x1800 when the answer is delivered.

The sprite table lives at 0xE0B0 (24 × 4 bytes) and 0x46BA flushes it every frame starting from a different one each time (0xE1B2 goes from 23 down to 0): the TMS9918's four-sprites-per-line limit rotates and no sprite is the one that always disappears.

The RAM map

All in 0xE000-0xE3FF, cleared by INIT. What matters:

   
0xE000 the game state, index into the table at 0x4226
0xE002 options: bit 4 keyboard, bit 5 two players, bit 6 game on, bit 7 the player
0xE008/9 the controls, before and now, in joystick format
0xE010 the three sound channels, 10 bytes each
0xE040 the high score; 0xE043 and 0xE046 each player's score (BCD, 6 digits)
0xE050 the player in play: lives, stage, extra life, new equation, solved, time, misses, symbols; 0xE080 the other one's copy
0xE0B0 the sprite table: 0-1 the monkey, 2-7 the crabs, 8-9 the professor, 10-17 the fruit, 18 the card
0xE108 the four actors, 8 bytes each, read from their sprite as IX+0x58
0xE140 the random seed
0xE142 the equation's result; 0xE144 the equation in symbols
0xE15A the ten cards of the stage (Y, X)
0xE1AF the card the monkey holds (0xFF none)
0xE1B5 / 0xE1C1 each player's equation; 0xE1CD/E the hidden digit
0xE1E4 / 0xE20E each player's cards: state and digit
0xE24C the state of each balloon
0xE260 the eight fruits: state and counter
0xE270, 0xE276 the answer's and the professor's flags

What it is made of

  bytes
code 8,962
data 7,422
unidentified 0

Of the data: 1,472 + 84 of compressed tiles (0x5156, 0x566B), 2,688 of sprites (0x56BF-0x5F5F), 504 of the title sign (0x4CD0), 1,044 of sound (0x7A71-0x7E85), 287 of 0xFF filler at the end, and the rest tables and lists: card positions per stage (0x50AE, 21 bytes each), platforms (0x6705), fruit (0x6806, 32 bytes per stage), flowers (0x6B42), equation scripts (0x712B), symbols (0x7207), the text of every sign and the tables of the two dispatchers.

There are five pieces of code nobody jumps to, seeded into the trace so they show as what they are: push iy / ret at 0x4072, a ld a,0F0h at 0x4917 that nobody uses, a list-driven platform painter (0x664F, 0x6624, 0x65F8) that 0x6685 left without a job, the entry of RLE_A_VRAM that reads the address ahead of the data (0x6C80), and nine bytes at 0x755C that fall into 0x7565.

The code

How the program is put together, with addresses. The names are the ones in the listing.

The interrupt is the program

INTERRUPCION (0x4038), every frame:

  1. acknowledges the VDP interrupt by reading its status;
  2. SUENA (0x796F), always;
  3. VUELCA_SPRITES (0x46BA), always;
  4. if 0xE005 is zero, sets it, enables interrupts and takes one step: LEE_MANDOS (0x41A7) from state 7 on and PASO_DEL_JUEGO (0x4209);
  5. restores everything and returns with reti.

PASO_DEL_JUEGO counts the clock (0xE003), blinks the 1UP during play, reads keys 1-5 outside it (TECLAS_1_A_5, 0x4678) and dispatches state 0xE000.

The dispatcher

DESPACHA (0x419D) is the call followed by a table: add a,a / pop hl / call HL_MAS_A / ld e,(hl) / inc hl / ld d,(hl) / ex de,hl / jp (hl). The return address is the table of words, so it never returns to the call. Two places use it: 0x4223 with the 20-state table at 0x4226, and 0x602B with the 11 actor states at 0x602E.

The twenty states

     
0 ESTADO_0_TITULO screen off, sprites and names cleared, music 0xA1 (which is silence)
2 ESTADO_2_LOGO the KONAMI rises one row every two frames (0x6C42)
3, 4 wait and ESTADO_4_TITULO the sign, one pixel row at a time (0x4C77)
5 ESTADO_5_MENU 256 frames of menu
6 ESTADO_6_DEMO_MONTA wipe, scoreboard and the equation 3 + ? = 5
1 ESTADO_1_GLOBOS the balloons rise (0x713D); the same state serves the demo and the game
7 ESTADO_7_DEMO the demo, with the inputs of the script at 0x4B78
18 ESTADO_18_OPCION the chosen option blinks for 0x60 frames
8 LEVEL_SELECT starts the game the first time, and keys 1-5
9 ESTADO_9_PLAYER_N spends the life, and PLAYER n / LEVEL n for 0x65 frames
10 ESTADO_10_MONTA_FASE cards, a new equation if due, shuffled digits, balloons
11 ESTADO_11_READY balloons, and READY counting down 15 seconds or until a button
12 ESTADO_12_PARTIDA the game
13 ESTADO_13_VIDA_O_RESUELTA life lost or equation solved; GAME OVER with no lives
14, 15 player swap and decide  
16 ESTADO_16_FASE_SUPERADA stage + 1 and back to LEVEL SELECT
17, 19 waits for the sound to end; 0x80 frames

States chain through SIGUIENTE_ESTADO (0x4661): most end with an inc (hl) on 0xE000. And one trap: ESTADO_9_PLAYER_N spends a life every time it is entered, so whoever goes there without having died (equation solved, 0x6E4A; stage cleared, 0x45C1) adds one first.

The actors

MONO_Y_CANGREJOS (0x4822) passes the controls to 0xE10B, repaints the cards every eight frames, checks the collision (0x69B0) and calls ACTOR_PASO (0x5F5F) with B = 1 (the monkey) and 2 to 4 (the crabs), the latter between one and four times per frame depending on the stage.

ACTOR_PASO sets IX to the actor's two sprites (0xE0B0 + 8(B−1)) and reads its record at IX+0x58..0x5F: facing, animation phase, type, state, timer, load. Before the state, the fruit: ACTOR_TOCA_FRUTA (0x6A4F) returns carry, D and E if one is within 0x16 pixels, and with that the actor picks it up (jumping), dies or loses a life (if it is in the air). Then the eleven states of 0x602E:

     
0 ACTOR_ESCONDIDO waits and appears at the top centre
1 ACTOR_PARADO fire jumps, a direction walks
2 ACTOR_ANDA one pixel, the animation, the floor and the edges
3 ACTOR_SALTANDO the table at 0x6423; at the top, the card; touching the professor, the delivery
4 ACTOR_SUBE_HUECO climbs through a gap in the platform above
5 ACTOR_SE_HUNDE comes down slowly with the card just grabbed
6 ACTOR_CAE_ESTADO four pixels a frame down to the floor
7 ACTOR_SE_DESCUELGA the crab crosses the top platform
8 ACTOR_TIRA_FRUTA the fruit flies off
9 CANGREJO_MUERE the 500 and back into hiding
10 ACTOR_LE_DA_LA_FRUTA fright and life lost

The stage's platforms are the only geometry: HAY_SUELO (0x6924) walks the list of (Y, X, width) at 0x66F5 looking for one at Y + 0x10 that covers the X, and HAY_PLATAFORMA_ARRIBA (0x696B) does the same upwards. There is no collision map: the table is consulted.

The cards and the answer

PINTA_TARJETAS (0x4EC8) walks the ten at 0xE15A and repaints those with bit 7: the bottom 3 − c rows of a 3×2 block (blank or with the digit, alternating) and the edge under it. The edge's position comes from PINTA_BLOQUE (0x6906) returning D advanced by as many rows as it painted; the 8c + Y computed at 0x4F42 stays in A and nobody uses it.

RESPONDE (0x7708) starts the blinking, TARJETA_COMPARA (0x7796) decides, and the answer card is sprite 18 driven by the bits of 0xE270 (TARJETA_PASO, 0x7834): 4 waits for the card to close, 3 falls, 1 rides on the monkey's head, 0 rises on its own. The professor (PROFESOR, 0x7473) watches the same bits.

The equation

GENERA_ECUACION (0x6F96) writes symbols into 0xE144 following the level's script (0x7117) with the BCD arithmetic of 0x6E6E-0x6EDB: add, subtract, multiply by repeated addition and division done backwards (D × E ÷ D = E). ELIGE_INCOGNITA (0x7253) covers a digit, MONTA_GLOBOS (0x7297) prepares a two-sprite balloon per symbol, off screen at the bottom, and GLOBOS_SUBEN (0x713D) releases them at random one at a time; GLOBO_LLEGA (0x71BF) paints the symbol in 2×2 where each one arrives.

AZAR (0x6F0D) mixes the seed at 0xE140 with the R register and with a word from the system ROM (0x0000-0x3FFF), and remixes with daa: the nibbles come out between 0 and 9, which is what the BCD arithmetic needs.

The sound

SONIDO (0x78DF) starts sound A if a game is on (SONIDO_YA, without checking). 1 to 0x10 are one-channel effects (channel C); 0x91 to 0x9B two-channel tunes, and from 0x9D three. The table at 0x7A7B gives the first channel's track and the following words the others', which is why tune numbers go in twos. Priority is by number: if the channel is playing something equal or higher, nothing, except 2, which always gets in. SUENA (0x796F) is the player: per channel a note counter, the track, octave, volume and an envelope of three steps down when the note starts and two at the end. Effects are volume/period pairs; music is notes in one nibble with the duration in the other over the period table at 0x7A71.

What gets painted

VPOKE (0x4082) and RELLENA_VRAM (0x48AA) are the base; PINTA_LISTA_TILES (0x48E9) walks lists of address + tiles with 0xFE to change place and 0xFF to end, and every sign is written with it. PINTA_BLOQUE (0x6906) paints B×C tiles at pixel coordinates, PINTA_RECUADRO (0x66BB) fills rectangles, PIXELS_A_VRAM (0x6605) turns (Y, X) into a name-table address. RLE_A_VRAM (0x6C84) decompresses the tiles, ESPEJA_SPRITES (0x4107) flips 22 sprites bit by bit, and TITULO_UNA_FILA (0x4C77) paints the title sign one pixel row every eight frames.

Code shared with other Konami cartridges

This disassembly has been compared, instruction by instruction, with every other Konami one in the series. A block counts when the same instructions, at least six of them from a label to its ret or its unconditional jump, are in both cartridges; the addresses are left aside, because they change from one cartridge to the next. Of the other 57, 31 have at least one block in common with this one; these are the ones that share the most:

Cartridge Blocks Instructions For example (here = there)
Athletic Land 17 255 SUENA_PASO (0x798B)
Cabbage Patch Kids 10 115 PINTA_BYTES_BCD (0x4A4F) = PINTA_BCD
Antarctic Adventure 9 184 MUSICA_EVENTO (0x7A10) = VOLUMEN_MIRA_FD
Super Cobra 9 136 MUSICA_EVENTO (0x7A10)
Konami’s Billiards 6 105 SUENA_PASO (0x798B) = paso_de_un_canal
Circus Charlie 6 49 PINTA_TILES_SEGUIDOS (0x6C71) = pinta_franja_correlativa
Magical Tree 5 53 PINTA_BYTES_BCD (0x4A4F) = imprime_bcd

The whole matrix, the 58 cartridges against each other, is on The routines in the series database, along with the method and the program that measures it.