← BLACKOUTASM StudioRU

BLACKOUT · Apple //c · 6502

Code Walkthrough

How the game works inside — from power-on to the finale. Each chapter has a picture, where the data lives, the order of calls, and one or two subroutines line by line, with real numbers. A 6502 instruction reference closes the book.

Chapter 0. Program map

Before diving into the subroutines, it helps to see the whole: what is on the disk, in what order it runs, where everything lives in memory, and what the main loop does. Everything else consists of subroutines that the main loop calls with JSR.

What is on the disk

FileWhat it isSectors
HELLOA two-line BASIC program. DOS runs it automatically at boot.2
INTROThe intro (intro.s). It stores no pictures itself — it loads them from the disk.6
INTRO1…7Intro frames, 8 KB each — exactly one HiRes page, byte for byte.7 × 34
CASCADEThe “wave” table that drives the grid going dark in the intro.3
MAINThe game itself: all the code (main.s and everything it includes).53
DATAGraphics, name syllables, texts, messages (data.s). No code.36
LEGENDThe finale picture, 8 KB.34
REG0…7, HEROCreated during play: region state and the saved game.—

A sector is 256 bytes, and the disk holds 560 of them. It is clear where the space goes: the intro and finale pictures take more room than the whole game.

How the game starts

DOS 3.3At power-on the ROM reads track 0 and DOS loads.
HELLOMAXFILES 1, then BRUN INTRO.
INTROIntro frames go straight into video memory with a DOS command. At the end, BRUN MAIN.
LC_LOADThe first thing MAIN does: BLOAD DATA to $2000 and a move into hidden memory.
SetupTables: screen rows, world seeds, substation, hero shifts, market.
TITLE → loopMenu N / C / Q, then the main loop: key → action → frame.

HELLO on the disk, in full:

10 PRINT CHR$(4);"MAXFILES 1"
20 PRINT CHR$(4);"BRUN INTRO"

CHR$(4) is Ctrl-D. DOS 3.3 watches everything printed to the screen, and if a line starts with Ctrl-D it executes that line as a command. The game uses the same trick: it prints Ctrl-D and a command through COUT, and DOS executes it. This is how the game loads DATA, saves, and reads region files.

Why MAXFILES 1. By default DOS keeps 3 buffers for open files in memory, 595 bytes each, located right below DOS. With a single buffer DOS starts at $9AA6 instead of $9600, which gives the game another 1,190 bytes. Without this line the game code, which ends at $937B, would stay intact, but the LOC_GROW3 table at $9980 would overlap the DOS buffers, and the very first disk access would corrupt it.

Memory map during play

The //c sees 64 KB at once. This is how they are divided. The address on the left is the start of each region.

$0000–$00FF
Zero pageThe most frequently used variables: the seed SEED $10–$17, pointers PTR, STR. Instructions with a zero page address are one byte shorter and one cycle faster.
256 B
$0100–$01FF
StackReturn addresses from JSR, PHA/PLA.
256 B
$0200–$03FF
Game variablesLOC_SRCH $0200 — “searched / visited” for every location; then assorted small items: page, key, hero, market.
512 B
$0400–$07FF
Text screen, page 1Only rows 20–23 are visible — the HUD below the picture.
1 KB
$0800–$0BFF
Text, page 2A copy of the HUD (for the second graphics page), and tables in the “invisible” rows: the screen map, settlement growth LOC_GROW, the backpack.
1 KB
$0C00–$13FF
WLD_TAB — region seeds256 locations × 8 bytes. Computed once on entering a region, then read instantly.
2 KB
$1400–$1F97
Hero: buffer and tablesA shifted copy of the frame, 7 shift tables ($1500–$1BFF), mirror, “x → byte and shift”.
3 KB
$2000–$3FFF
HiRes page 1At startup DATA is loaded here first — the screen is not needed yet.
8 KB
$4000–$5FFF
HiRes page 2While one page is shown, drawing happens on the other. Region files and the saved game are also read here temporarily.
8 KB
$6000–$937B
MAIN — game code13,180 bytes. About 1.5 KB more is free up to $997F.
13 KB
$9980–$9A7F
LOC_GROW3Growth of the third settlement in every location.
256 B
$9AA6–$BFFF
DOS 3.3Off limits: overwriting it stops the disk drive from working.
9 KB
$C000–$CFFF
Input/outputNot memory but “switches”: accessing an address turns something on. Keyboard $C000, screen pages $C054/$C055, hidden memory $C080…
4 KB
$D000–$FFFF
ROM — and the language card behind itNormally the ROM is visible here: BASIC and the monitor (COUT, HOME, WAIT…). But the same addresses also hold 16 KB of RAM that is enabled by a switch. DATA is moved there at startup ($D000–$F255).
12+16 KB

The main constraint is obvious: code only has the stretch between the second graphics page and DOS — 14,720 bytes. That is why everything that is not code (pictures, syllables, texts) lives in the language card. Without it the game would not fit.

How it is built: two files, two addresses

The project has 34 files, but they assemble into exactly two programs:

MAIN reaches data in DATA through addresses written in vars.s (CHR_TAB = $D000, TILE_TAB = $DC00…). If DATA is rebuilt and something shifts, the addresses no longer match. So after any change to DATA, the addresses in vars.s must be checked against where the labels actually ended up — the assembler listing shows them.

Rules the whole code follows. The main loop is nothing but JSR. Every subroutine has a header: what it does, input, output, what it clobbers. Names carry a module prefix (WLD_… — world, HERO_… — hero, MKT_… — market). Inside subroutines, local labels start with @: @loop in one subroutine does not clash with @loop in another. No “bare” numbers — addresses have names in vars.s.

Setup: start

The beginning of main.s. Each line is one subroutine, and each has its own chapter.

start:
        JSR LC_LOAD             ; DATA from disk → language card          (chapter 0, below)
        JSR SCR_ROWS            ; “row → address” table for HiRes          (chapter 4)
        LDA #0                  ; region 0 — Catalonia
        STA REGION
        JSR WLD_FILL            ; 256 region seeds into WLD_TAB              (chapter 1)
        JSR SUB_INIT            ; where the substation is                   (chapter 12)
        JSR HERO_PREP           ; hero shift tables                         (chapter 5)
        JSR MKT_INIT            ; money, backpack, markets                  (chapter 9)
        LDA #$FF
        STA NSELF               ; collision check: no “self”                (chapter 7)
        LDA #P_WALK
        STA WMASK               ; the hero may step on “walkable”
        JSR TITLE               ; menu: N → C = 0, C (continue) → C = 1     (chapter 15)
        BCC @newgame
        JMP @key                ; continued — screen already shown, straight into the loop

Note the BCC after JSR TITLE. This technique appears throughout the game: a subroutine answers “yes / no” with the carry flag C. CLC before RTS means “no”, SEC means “yes”, and the caller branches right away with BCC/BCS. The registers stay free for real data.

New game: reputation 8 / 4 / 8 (guards, raiders, residents), starting location $37 — row 3, column 7 on the 16 × 16 map — and a jump to @enter.

Entering a screen: @enter

@enter:
        LDA #4                  ; screen 4 — the centre of the 3 × 3 square (0 1 2 / 3 4 5 / 6 7 8)
        STA GSCR
        JSR LOC_LOAD            ; everything about location HERE: seed, type, name, settlements
        JSR SCR_GEN             ; screen map: 20 × 10 tile numbers
        JSR OBJ_CLEAR           ; remove the previous screen’s NPCs
        JSR HERO_SPAWN          ; a walkable spot for the hero
        JSR OBJ_GEN             ; NPCs of this screen
        LDA #0
        STA DPAGE               ; draw on page 1
        STA LASTK               ; no “last key”
        JSR SCR_CLEAR
        JSR SCR_ON              ; turn on HiRes + 4 text rows
        JSR HOME
        JSR SCR_SHOW            ; HUD, both pages, hero

The order matters: first compute the screen (what stands where), then place the hero and NPCs on free cells, and only then draw. Drawing decides nothing — it only shows what is already in the tables.

Town screen: houses, trees, the hero on a road, HUD at the bottom
The result of @enter: the top 160 lines are HiRes, with 4 text rows (the HUD) below. This is the Apple II “mixed mode”.

Main loop: @key

From here the program spins in a single loop. One pass is one key (or none) and one frame.

@key:
        JSR CMB_TICK            ; resting: health slowly recovers
        LDA KBD                 ; $C000: a new key?
        BMI @new                ; bit 7 = 1 → yes
        BIT KBDSTRB             ; $C010: bit 7 = key still held down
        BPL @none
        LDA KBD
        ORA #%10000000
        CMP LASTK               ; the same one already handled?
        BEQ @walk               ; yes — it is held: keep walking
@new:
        STA LASTK
        STA KBDSTRB             ; “key has been read”
        CMP #$A0                ; space → market or search
        ...

This is the trickiest part of the chapter. First, what the keyboard byte contains and what ORA does to it; then the whole loop with numbers.

Keyboard byte $C000 — what it holds

bit
7
6
5
4
3
2
1
0
LDA KBD
1
0
0
1
0
1
0
1
$95 ← new, not yet read
after STA KBDSTRB
0
0
0
1
0
1
0
1
$15 ← bit 7 cleared: “already read”

Bit 7 is the “unread key waiting” flag. Bits 0–6 are the code itself: $15 is the right arrow (same as Ctrl-U). A write to $C010 (STA KBDSTRB) clears the flag and keeps the code. That is why A holds sometimes $95 and sometimes $15 in the loop — it is the same key, before and after “read”.

ORA #%10000000 — “set bit 7”

bit
7
6
5
4
3
2
1
0
A
0
0
0
1
0
1
0
1
$15
ORA
1
0
0
0
0
0
0
0
$80
= A
1
0
0
1
0
1
0
1
$95

ORA is OR on each bit separately, column by column: the result is 1 if at least one of the two is 1. The mask $80 has a one only in bit 7. So bit 7 becomes 1 and the other 7 bits stay as they were. This turns the “read” $15 back into $95 — the form stored in LASTK.

bit
7
6
5
4
3
2
1
0
A
1
0
0
1
0
1
0
1
$95
AND
0
0
0
1
1
1
1
1
$1F
= A
0
0
0
1
0
1
0
1
$15

For comparison, AND: 1 only where both are 1. The mask keeps the wanted bits and clears the rest. In the game this means “extract part of a byte”: AND #%00011111 takes bits 0–4 (a number 0–31), which is how name syllables are chosen in chapter 2. A rule to remember: ORA sets the mask bits, AND keeps the mask bits, EOR flips the mask bits.

Now step by step. The right arrow is pressed and held.

LineRegistersWhat happens
LDA KBDA = $95The right arrow is code $15. Until the key is “read”, the keyboard holds bit 7 set: $15 + $80 = $95. Bit 7 = 1, so the number is “negative”.
BMI @new→ @newBMI branches if N = 1 (bit 7 of the result). A new key.
STA LASTKLASTK = $95Remember that this one has been handled.
STA KBDSTRBA write to $C010 clears bit 7 in $C000. Now LDA KBD returns $15 — “old”.
… the hero has taken a step, the frame is drawn, next pass of the loop. The key is still held.
LDA KBDA = $15Bit 7 = 0 — no new key.
BMI @newno branch
BIT KBDSTRBN = 1On the //c, bit 7 of a read from $C010 tells whether any key is held down right now (AKD — any key down). BIT puts bit 7 of the value read into the N flag without touching A.
BPL @noneno branchHeld.
ORA #%10000000A = $95Bit 7 restored, to compare with what is stored in LASTK.
CMP LASTK$95 = $95The same key.
BEQ @walk→ @walkIt is held — the hero keeps walking, with no delayed auto-repeat.

Flags and CMP — what every “if” rests on

The 6502 has no “if A = 5, jump” instruction. There are two halves: one instruction sets the flags, the next one looks at a flag and branches or not. The flags are a separate byte P, the status register:

bit
7
6
5
4
3
2
1
0
P
N
V
–
B
D
I
Z
C
highlighted: the ones needed almost everywhere

N (negative) is a copy of bit 7 of the result. Z (zero) means the result is zero. C (carry): in addition, “went past 255”; in a comparison, “A is not less”. Almost every instruction that puts something into a register sets flags: LDA, AND, ORA, INX, DEX… while STA, JSR, BEQ leave them alone.

This is how LDA KBD / BMI @new in the loop works: LDA put $95 into A and copied bit 7 into N; BMI (“branch if minus”) branches if N = 1. BIT KBDSTRB is special: it puts bit 7 of the byte read into N, bit 6 into V, and does not touch A at all.

CMP — subtract, but discard the answer

CMP LASTK computes A − LASTK but stores the result nowhere — A stays unchanged. Only the flags remain from the subtraction. Three cases with numbers:

1. Equal: A = $95, LASTK = $95

bit
7
6
5
4
3
2
1
0
A
1
0
0
1
0
1
0
1
$95
− LASTK
1
0
0
1
0
1
0
1
$95
= (discarded)
0
0
0
0
0
0
0
0
$00 Z = 1 (zero) · C = 1 · N = 0

The difference is 0 → Z = 1. BEQ @walk (“branch if equal” = “if Z = 1”) branches: the same key, being held.

2. A is greater: A = $95, the table holds $88

bit
7
6
5
4
3
2
1
0
A
1
0
0
1
0
1
0
1
$95
− KEY_DIR,X
1
0
0
0
1
0
0
0
$88
=
0
0
0
0
1
1
0
1
$0D Z = 0 · C = 1 (no borrow) · N = 0

$95 − $88 = $0D, not zero → Z = 0, BEQ does not branch: “wrong arrow, keep looking”. C = 1 means “A ≥ the value compared against” — the subtraction needed no borrow.

3. A is less: A = $88, compared with $95

bit
7
6
5
4
3
2
1
0
A
1
0
0
0
1
0
0
0
$88
−
1
0
0
1
0
1
0
1
$95
=
1
1
1
1
0
0
1
1
$F3 Z = 0 · C = 0 (borrow) · N = 1

$88 − $95 “does not fit” in a byte: the result is $F3 (like a counter that rolled past zero) and C = 0 — there was a borrow. That is exactly “A is less”. N = 1 here is incidental — just bit 7 of the difference; comparisons of numbers ignore it.

What can be tested after CMP:

BranchFlagMeaning$95 vs $95$95 vs $88$88 vs $95
BEQZ = 1A = Mbranchesnono
BNEZ = 0A ≠ Mnobranchesbranches
BCSC = 1A ≥ Mbranchesbranchesno
BCCC = 0A < Mnonobranches

Nothing more is needed: “greater”, “less” and “equal” anywhere in the game are CMP plus one of these four branches. For example, HERO_PREP in chapter 5 has CMP #7 / BCC — “if the shift is less than 7”. X and Y can be compared too: CPX and CPY work exactly the same way — like CPX #6 / BNE @loop in the seed step (chapter 1): “loop until X reaches 6”.

An important detail. Flags last until the next instruction that sets them. An LDA, for example, cannot be placed between CMP and BEQ — it would overwrite Z, and the branch would test the loaded number instead. That is why in the code the branch almost always follows the comparison directly.

Why all this complexity around the key? The standard Apple II auto-repeat first waits half a second and then repeats slowly — the hero would move in jerks. Here “arrow held” is read directly, and the hero walks smoothly, frame by frame. On release, BIT KBDSTRB gives N = 0, the code branches to @none, LASTK is cleared, and the next press of the same arrow counts as “new” again.

Who handles which key

KeyCodeHandler
space$A0ACT_KEY — market in a settlement, search outside it (chapter 9)
A, W, M, I$C1 $D7 $CD $C9CMB_KEY — punch, weapon attack, medicine, status window (lowercase too). Returns C = 1 if the key is “its own” (chapters 10–11)
Return$8D@map → MAP_VIEW — region map (chapter 13)
↑ → ↓ ←$8B $95 $8A $88looked up in the KEY_DIR table; index 0–3 → HERO_MOVE (chapters 5–6)
nothing@idle → HERO_FRAME: the hero stands, NPCs walk

The arrow lookup is a small example of how a “switch” is done on the 6502: not a chain of comparisons, but a table and a loop over it.

@walk:
        LDX #3                  ; X = 3, 2, 1, 0
@dir:
        CMP KEY_DIR,X           ; A = key code; KEY_DIR = $8B $95 $8A $88
        BEQ @go                 ; found: X is the direction index
        DEX
        BPL @dir                ; X became $FF — bit 7 = 1, loop over
        JMP @idle
        ...
@go:
        TXA                     ; A = direction 0–3 (↑ → ↓ ←)
        JSR HERO_MOVE
        LDA #30
        JSR WAIT                ; ROM delay — walking speed
        JMP @key

Right arrow, A = $95: X = 3 — $88, no; X = 2 — $8A, no; X = 1 — $95, match. HERO_MOVE receives A = 1, “right”. The clockwise order ↑ → ↓ ← is the same throughout the game: in screen exits, in roads, on the map.

LC_LOAD: how DATA gets into hidden memory

The very first subroutine. Two parts: ask DOS to load the file, then move it.

LC_LOAD:
        LDX #0
@cmd:
        LDA TXT_BLOAD,X         ; $8D $84 "BLOAD DATA,A$2000" $8D 0
        BEQ @copy               ; 0 — end of string
        JSR COUT                ; print it — DOS sees Ctrl-D and executes
        INX
        BNE @cmd
@copy:
        BIT LCWR                ; $C081 — twice in a row:
        BIT LCWR                ; read from ROM, write to hidden RAM
        ...                     ; PTR = $2000 (source), PTR2 = $D000 (destination)
        LDX #LC_PAGES           ; 35 pages of 256 bytes
        LDY #0
@page:
        LDA (PTR),Y
        STA (PTR2),Y
        INY
        BNE @page               ; 256 bytes of a page
        INC PTR+1               ; $20 → $21: next page
        INC PTR2+1              ; $D0 → $D1
        DEX
        BNE @page
        LDX #5
@vec:
        LDA $FFFA,X             ; read ROM …
        STA $FFFA,X             ; … write hidden RAM
        DEX
        BPL @vec
        BIT LCROM               ; $C082: back to normal — read ROM
        RTS

LDA TXT_BLOAD,X — “take byte number X of the string”

TXT_BLOAD is not a variable but a label: the name of the address where the assembler placed the string bytes. In the assembled MAIN it is $9367. This is how the string sits in memory:

$93678DReturnX = 0
$936884Ctrl-DX = 1
$9369C2BX = 2
$936ACCLX = 3
$936BCFOX = 4
$936CC1AX = 5
$936DC4DX = 6
$936EA0spaceX = 7
$936FC4DX = 8
$9370C1AX = 9
…
$937A8DReturnX = 19
$937B00endX = 20

LDA TXT_BLOAD,X = “load A with the byte at address $9367 + X”. The address in the instruction is fixed; only X changes:

XAddressANext
0$9367 + 0 = $9367$8Dnot 0 → JSR COUT prints Return, INX
1$9367 + 1 = $9368$84prints Ctrl-D — DOS gets ready
2$9369$C2“B”
………“LOAD DATA,A$2000”
19$937A$8DReturn — DOS executes the command, the file loads
20$937B$00LDA set Z = 1 → BEQ @copy: end of string

Where does X come from? Nobody passes it in — the first line of LC_LOAD sets LDX #0 itself. Here X is a counter of “which byte”, not an input of the subroutine. LC_LOAD takes no input: its header says only “clobbers: A, X, Y…”.

Why is “B” $C2 and not $42? The Apple II screen shows normal text when bit 7 of the character code is set. $42 + $80 = $C2. The assembler adds this bit itself in .asc; Return is $0D + $80 = $8D, Ctrl-D is $04 + $80 = $84.

What the instruction looks like in memory. LDA TXT_BLOAD,X is three bytes: BD 67 93. BD is the opcode for “LDA address,X”, followed by the address backwards: low byte $67, then high byte $93. The 6502 always stores 16-bit addresses this way — low byte first.

From then on the game reads DATA like this: BIT LCRAM (enable reading hidden RAM) — a few instructions — BIT LCROM (bring the ROM back). While hidden RAM is enabled, the ROM is not visible, so COUT, WAIT and other ROM routines must not be called — at that moment they simply are not there. The whole code follows this rule.

Chapter 1. Seed and world

A region has 256 locations, and each one has a type, an "order" level, a terrain, a name, settlements, roads and prices. None of this is stored in the code or on the disk. Everything is computed from 8 bytes — the region seed. This is the same trick that let Elite fit eight galaxies into the 32 KB of a BBC Micro in 1984.

This chapter covers where the seed lives, how one step is made, how a 16-bit number is added on an 8-bit processor, why a location takes exactly four steps, and where the type, order and terrain come from.

The seed in memory

The seed is four 16-bit numbers: S0, S1, S2, S3. The processor works only with bytes, so each word takes two cells: low byte first, then high byte — the same as the address in the instruction BD 67 93 from chapter 0. The seed lives in zero page at $10–$17. This is the Catalonia seed right after WLD_INIT:

$104AS0 loSEED
$115AS0 hiSEED+1
$1248S1 loSEED+2
$1302S1 hiSEED+3
$1453S2 loSEED+4
$15B7S2 hiSEED+5
$162ES3 loSEED+6
$171FS3 hiSEED+7

It reads as S0 = $5A4A, S1 = $0248, S2 = $B753, S3 = $1F2E. The first three numbers are the same as in Elite. The code refers to the bytes by the name SEED plus an offset: SEED+1 is the high byte of S0, SEED+7 the high byte of S3. This is not arithmetic at run time: the assembler substitutes $11 and $17 itself.

One step: WLD_STEP

The step rule is simple: add all four numbers, shift them one place to the left, and put the sum last.

T  = S0 + S1 + S2 + S3        ; all modulo $10000 — the carry out of bit 16 is lost
S0 ← S1,  S1 ← S2,  S2 ← S3,  S3 ← T

This is "tetranacci" — like Fibonacci, but four numbers are added instead of two. Elite used "tribonacci" on three numbers. Here are the first steps on the Catalonia seed:

StepS0S1S2S3Sum→ new S3
0$5A4A$0248$B753$1F2E$13313$3313
1$0248$B753$1F2E$3313$10BDC$0BDC
2$B753$1F2E$3313$0BDC$11570$1570
3$1F2E$3313$0BDC$1570$0738D$738D
4$3313$0BDC$1570$738D← this is the seed of location 1: all four numbers are new

The sum can exceed $FFFF — $13313. The extra 1 on the left simply disappears. That is intended: the number stays 16-bit, and the "wrap through zero" mixes the bits even better.

16-bit addition on an 8-bit processor

The 6502 adds only bytes. A 16-bit addition is two additions: the low bytes first, then the high bytes, with the carry — the C flag from chapter 0 — passed between them. The ADC instruction adds three things: A + operand + C. That is why the first addition is always preceded by CLC: clear C so that a stray 1 is not added.

Take the most interesting part of step 0 — the third addition. WTMP already holds S0 + S1 + S2 = $13E5, and S3 = $1F2E is added to it.

Low bytes: $E5 + $2E

bit
7
6
5
4
3
2
1
0
A = WTMP
1
1
1
0
0
1
0
1
$E5
ADC SEED+6
0
0
1
0
1
1
1
0
$2E
+ C
0
0
0
0
0
0
0
0
0 after CLC
= A
0
0
0
1
0
0
1
1
$13 and C = 1: $E5 + $2E = $113 — the ninth bit went into the carry

229 + 46 = 275. A byte holds up to 255, so A keeps 275 − 256 = 19 = $13, and the "extra 256" is remembered as C = 1.

High bytes: $13 + $1F + carry

bit
7
6
5
4
3
2
1
0
A = WTMP+1
0
0
0
1
0
0
1
1
$13
ADC SEED+7
0
0
0
1
1
1
1
1
$1F
+ C
0
0
0
0
0
0
0
1
1 the carry from the low bytes
= A
0
0
1
1
0
0
1
1
$33 C = 0

Result: $33 and $13 → $3313, matching the table. There is no second CLC between the two ADCs: the carry has to reach the high byte. If it were cleared, the result would be $3213 — 256 too small.

        CLC                     ; C = 0 — only before the low bytes
        LDA WTMP
        ADC SEED+6              ; low byte of S3
        STA WTMP
        LDA WTMP+1
        ADC SEED+7              ; high byte of S3 + carry
        STA WTMP+1

LDA and STA between the two ADCs do not touch the C flag. This matters: if an instruction that changes C (for example CMP) stood between them, the carry would be lost.

Shifting the words: S0 ← S1 ← S2 ← S3

After the sum, the numbers are moved one place. That is six bytes moving two cells to the left — the same X-counter loop as in LC_LOAD:

        LDX #0
@loop:
        LDA SEED+2,X           ; X = 0: take $12 (S1 lo) …
        STA SEED,X             ;       … store to $10 (S0 lo)
        INX
        CPX #6                 ; 6 bytes: X = 0…5
        BNE @loop
        LDA WTMP                ; and only now T → S3 ($16/$17)
        STA SEED+6
        LDA WTMP+1
        STA SEED+7

Step 0, before and after the loop:

$104AS0
$115A
$1248S1
$1302
$1453S2
$15B7
$162ES3
$171Fbefore
$1048S0X=0
$1102X=1
$1253S1X=2
$13B7X=3
$142ES2X=4
$151FX=5
$1613S3T
$1733after

Why is T not stored in S3 right after the addition? Because the shift loop reads S3 ($16/$17) to move it into S2. If T were stored there first, T would end up in S2 instead of the old S3. Hence the comment in the code: "S3 ← T — the shift is already done, otherwise it would overwrite T".

Why four steps per location, and why the high bytes

The seed of location n is the region seed after 4·n steps. Why not one? After a single step, neighbouring locations share three of the four numbers, just shifted: S1 of location n would become S0 of location n+1. Neighbours would look alike. After 4 steps all four numbers are new — the table above shows this clearly.

The second subtlety is that the game uses almost only the high bytes of the words. The low bit of a sum depends only on the low bits of the addends, and it repeats very quickly. Here is bit 0 of the first 30 sums on the Catalonia seed:

bit 0:   10010 10010 10010 10010 10010 10010     ; repeats every 5 steps
bit 1:   1000001011 1000001011 1000001011        ; every 10
bit 8:   11111011000101001011111110100 0
bit 13:  10010010011110110011111000011 1          ; no visible repeat

If the location type were taken from the low bits, the types would cycle: anarchy, village, town, anarchy, village… The high bits collect the carries from all the lower positions and look random.

What the 64 bits of a location encode

Take location $37 — the one where the game starts. After 4 × 55 = 220 steps its seed is S0 = $BA42, S1 = $7E80, S2 = $93A3, S3 = $7586. The high bytes: $BA $7E $93 $75. This is what is extracted from them:

S0 high ($BA) — type, order, terrain

bit
7
6
5
4
3
2
1
0
SEED+1
1
0
1
1
1
0
1
0
$BA
type: AND #%11
0
0
0
0
0
0
1
0
2 0 ANARCHY · 1 RURAL · 2 INDUSTRIAL · 3 DEVELOPED
order
0
0
0
0
0
1
1
0
6 bits 2–4: 0 — a gang, 7 — a council and guards
terrain
0
0
0
0
0
1
0
1
5 bits 5–7: the background of the screens (chapter 3)

One byte, three properties. The type takes bits 0–1 (four values), the order bits 2–4 (eight values), the terrain bits 5–7. To extract a field, the byte is shifted right until the field reaches bit 0, then trimmed with an AND mask.

WLD_TYPE:
        LDA SEED+1
        AND #%00000011          ; keep bits 0–1
        RTS

WLD_ORDER:
        LDA SEED+1
        LSR A                   ; shift right by 2: bits 2–4 → 0–2
        LSR A
        AND #%00000111          ; keep bits 0–2
        RTS

WLD_ORDER on $BA: two LSRs and a mask

bit
7
6
5
4
3
2
1
0
LDA SEED+1
1
0
1
1
1
0
1
0
$BA
LSR A
0
1
0
1
1
1
0
1
$5D all bits one place right, bit 0 (0) goes to C, a 0 enters on the left
LSR A
0
0
1
0
1
1
1
0
$2E the order field is now in bits 0–2
AND #%111
0
0
0
0
0
1
1
1
$07
= A
0
0
0
0
0
1
1
0
6 order 6

LSR is "logical shift right": every bit moves one place to the right, bit 0 drops into the C flag, and a 0 enters bit 7. One LSR is division by 2 without remainder. Its partner ASL shifts left and multiplies by 2 — it is needed below.

The other high bytes, briefly — each is covered in detail in its own chapter:

ByteAt $37BitsMeaningChapter
SEED+3 (S1 hi)$7E0–4 · 5 · 4–7start of the name (30 = QUINTA) · whether there is a middle (yes) · what the market produces2, 9
SEED+5 (S2 hi)$930–4 · 4–7 · allmiddle of the name (19 = MA) · what the market needs · mix for the screen generator2, 3, 9
SEED+7 (S3 hi)$750–4 · allend of the name (21 = TERA) · mix for the screen generator2, 3
low bytes$42 $80 $A3 $86mixed with the high bytes (EOR): which of the 9 screens hold settlements3

QUINTA + MA + TERA, INDUSTRIAL — exactly what the HUD shows in the game. The fields overlap (bits 4–5 of byte S1 are used by both the name and the market), but that is harmless: the properties are just slightly correlated, and in play this is not noticeable.

The world table: WLD_FILL

Running 4·n steps every time location n is needed is slow: for location 255 that is 1,020 calls to WLD_STEP. So on entering a region, WLD_FILL walks through all 256 locations once and stores their seeds in the table WLD_TAB, 8 bytes each: 2 KB, $0C00–$13FF. At 1 MHz this takes about 0.15 seconds.

WLD_FILL:
        JSR WLD_INIT            ; SEED = region seed = location 0
        LDA #<WLD_TAB           ; PTR = $0C00: low byte $00 …
        STA PTR
        LDA #>WLD_TAB           ; … and high byte $0C
        STA PTR+1
        LDA #0
        STA WCNT                ; location counter
@loc:
        LDY #0
@byte:
        LDA SEED,Y              ; 8 seed bytes …
        STA (PTR),Y            ; … into the table via the pointer
        INY
        CPY #8
        BNE @byte
        CLC                     ; PTR = PTR + 8 (16 bits)
        LDA PTR
        ADC #8
        STA PTR
        LDA PTR+1
        ADC #0                  ; only the carry goes to the high byte
        STA PTR+1
        JSR WLD_STEP            ; next location — 4 steps
        JSR WLD_STEP
        JSR WLD_STEP
        JSR WLD_STEP
        INC WCNT
        BNE @loc                ; 256 rounds: after 255, INC gives 0
        RTS

Three new details appear here.

#<WLD_TAB and #>WLD_TAB. WLD_TAB = $0C00 is a 16-bit number, and A holds only a byte. The < sign tells the assembler "take the low byte" ($00), > "the high byte" ($0C). This way two instructions place an address into the cell pair PTR/PTR+1 ($06/$07).

STA (PTR),Y — a store through a pointer. Compare it with LDA TXT_BLOAD,X from chapter 0: there the address was built into the instruction. Here the instruction holds only the number of the zero page cell where the address is stored. The processor first reads two bytes from $06/$07, assembles an address from them, adds Y — and only then writes. The pointer can be moved without changing the instruction: the same STA (PTR),Y writes to location 0 and to location 255.

$0608PTRlo
$070CPTR+1hi
→
$0C0813Y=0
$0C0933Y=1
$0C0ADCY=2
…
$0C0F73Y=7

Example — the second round (location 1, seed $3313 $0BDC $1570 $738D): PTR already holds $0C08. With Y = 0, STA (PTR),Y writes $13 to $0C08 + 0; with Y = 7 it writes $73 to $0C0F. The parentheses in the notation mean "the address is stored there".

ADC #0 on the high byte. Adding 8 to a 16-bit number: low byte + 8, high byte + 0 + carry. While the low byte does not overflow ($00, $08, …, $F8), the carry is 0 and the high byte stays put. On round 32, $F8 + 8 = $100 → low byte $00, C = 1, and ADC #0 turns the high byte $0C into $0D. This is the same column addition as in the seed step, with $0008 as the second addend.

INC WCNT / BNE @loc. The counter starts at 0. A byte never exceeds 255: after 255, INC gives 0 and sets Z = 1. So BNE releases the loop after exactly 256 rounds — without a separate "CMP #256", which could not even be encoded in a byte.

Fetching a seed: WLD_GET and multiplying by 8 with shifts

When the hero enters location n, WLD_GET copies its 8 bytes from the table into SEED. Address = $0C00 + n × 8. The 6502 cannot multiply, but it can shift: ASL is ×2, three times is ×8. The problem is that n × 8 can exceed 255 ($37 × 8 = $1B8), while A is a single byte. The bit that falls out on the left has to be caught:

WLD_GET:
        LDX #0
        STX PTR+1         ; high byte = 0
        ASL A             ; ×2, bit 7 → C
        ROL PTR+1         ;     C → bit 0 of the high byte
        ASL A             ; ×4
        ROL PTR+1
        ASL A             ; ×8
        ROL PTR+1
        STA PTR           ; low byte of n × 8
        ...               ; + WLD_TAB, then 8 bytes (PTR),Y → SEED

n = $37: three ASL / ROL pairs

bit
7
6
5
4
3
2
1
0
A = n
0
0
1
1
0
1
1
1
$37
PTR+1
0
0
0
0
0
0
0
0
$00
ASL A
0
1
1
0
1
1
1
0
$6E bit 7 = 0 falls out → C = 0
ROL PTR+1
0
0
0
0
0
0
0
0
$00 C (0) enters bit 0
ASL A
1
1
0
1
1
1
0
0
$DC a 0 falls out → C = 0
ROL PTR+1
0
0
0
0
0
0
0
0
$00
ASL A
1
0
1
1
1
0
0
0
$B8 a 1 falls out → C = 1
ROL PTR+1
0
0
0
0
0
0
0
1
$01 C (1) enters bit 0

Result: PTR+1 = $01, PTR = $B8 → $01B8 = 440 = 55 × 8. Correct. ROL ("rotate left") differs from ASL in one way: bit 0 receives the old value of C instead of 0. The pair ASL A / ROL PTR+1 works as one 16-bit shift: the bit that falls out of the low byte travels through C into the high byte.

Next, + WLD_TAB is an ordinary 16-bit addition: $01B8 + $0C00 = $0DB8. At this address the table holds the seed of $37: $42 $BA $80 $7E $A3 $93 $86 $75.

Neighbours on the map: number = row × 16 + column

A region is a 16 × 16 grid, and the location number is laid out very conveniently: the high 4 bits are the row, the low 4 bits the column. The hexadecimal notation shows the coordinates directly.

0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
0
00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
1
10
11
12
13
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F
2
20
21
22
23
24
25
26
27↑ $27 = −16
28
29
2A
2B
2C
2D
2E
2F
3
30
31
32
33
34
35
36← $36 = −1
37
38→ $38 = +1
39
3A
3B
3C
3D
3E
3F
4
40
41
42
43
44
45
46
47↓ $47 = +16
48
49
4A
4B
4C
4D
4E
4F
5
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
6
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
7
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
8
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
9
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
A
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF
C
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E
E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
$37 — row 3, column 7: all four neighbours exist. Right +1, left −1, down +16, up −16.
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
0
00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
1
10
11
12
13
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F
2
20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F↑ $2F
3
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E← $3E
3F
4
40$3F+1 = $40 ✗
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F↓ $4F
5
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
6
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
7
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
8
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
9
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
A
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF
C
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E
E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
$3F — the right edge (column F). Up, down and left work as usual. But "+1" would give $40 — already the next row, at the left edge. That is why WLD_RIGHT checks the column first.

$37 — row 3, column 7

bit
7
6
5
4
3
2
1
0
n
0
0
1
1
0
1
1
1
$37 left 0011 = row 3, right 0111 = column 7
AND #%1111
0
0
0
0
1
1
1
1
$0F
= column
0
0
0
0
0
1
1
1
7 not 15 → there is a neighbour on the right

From this come all four neighbours: right — n + 1 ($38), left — n − 1 ($36), down — n + 16 ($47), up — n − 16 ($27). The map edge is column 15 (right), column 0 (left), n ≥ 240 (bottom row), n < 16 (top row).

WLD_RIGHT:
        STA WTMP          ; remember n
        AND #%00001111    ; column
        CMP #15
        BEQ @edge         ; right edge
        LDA WTMP
        CLC
        ADC #1            ; n + 1
        CLC               ; answer: allowed
        RTS
@edge:
        LDA WTMP          ; the number is unchanged
        SEC               ; answer: edge
        RTS

Again the answer is returned in the C flag, as with TITLE in chapter 0: C = 0 means "allowed, here is the number", C = 1 means "edge". Note the two CLCs: the first comes before the addition (so that no extra 1 is added), the second serves as the answer, because ADC could leave anything in C. WLD_DOWN checks its edge differently — CMP #240 / BCS @edge: "if n ≥ 240" is the row "BCS = A ≥ M" from the branch table in chapter 0.

Eight regions: WLD_INIT

Each region has its own seed in the table REG_SEEDS (in region.s), 8 consecutive bytes. WLD_INIT copies the right 8 bytes into SEED:

WLD_INIT:
        LDA REGION              ; 0–7
        ASL A                   ; × 8: start of the seed in the table
        ASL A
        ASL A
        TAY                     ; Y = 0, 8, 16 … 56
        LDX #0
@loop:
        LDA REG_SEEDS,Y         ; read from this region's place in the table …
        STA SEED,X             ; … write from the start of SEED
        INY
        INX
        CPX #8
        BNE @loop
        RTS

There are two indexes at once: Y says where to read (Aragon, REGION = 1, starts at Y = 8), X says where to write (always from 0). Here ASL needs no ROL partner: 7 × 8 = 56 fits in a byte. The region seeds were chosen by hand, except for Catalonia, which starts with the Elite numbers. When the region changes, WLD_FILL runs again, and 256 new locations are ready.

Chapter 2. Names from syllables

Each of the 2,048 locations has a name — VILLAZAR, BENADILLA, QUINTAMATERA. None of them is stored. A name is assembled from pieces chosen by seed bits, anew every time it has to be printed: on the HUD, on the map, at the market.

Elite named its planets with letter pairs: LAVE, DISO, RIEDQUAT. Here the pieces are longer — Spanish-sounding syllables of three kinds: a start, a middle (not always present) and an end. There are 32 of each.

Three tables of 32 pieces

The pieces of the starting location $37 are highlighted. The small number is the piece number (why middles start at 32 and ends at 64 is explained below).

Starts, 0–31

0SAN1VAL2VILLA3ALCA4TORRE5MON6CAR7BAR8PUEBLA9CASA10ARRO11BENA12GRANA13LOS14MAR15SOTO16ALBA17MEDI18PENA19FUEN20CAMPO21OLI22ROBLE23SALA24CUEVA25LAGU26HOR27NAVA28PALO29ESPI30QUINTA31RIVA

Middles, 32–63

32TA33RE34LA35MO36NI37DE38RI39BE40GA41LO42TO43RA44SE45CO46NA47VE48LLE49BI50DU51MA52PI53SO54TI55CA56RU57DI58BO59NO60LU61JE62FE63GO

Ends, 64–95

64REJO65LLA66DA67NES68RA69TOS70LAR71DO72SA73NA74RES75LLO76GA77CIA78TE79JAR80NUEVA81MOR82LES83DILLA84RAL85TERA86NAS87DERA88LEJA89VAL90CINA91DOSA92RIA93TAL94LON95ZAR

Start + end gives 32 × 32 = 1,024 names; with a middle, another 32 × 32 × 32 = 32,768. Of the 256 locations in Catalonia, 252 have distinct names; there are only four duplicate pairs (OLITERA, BARVAL, CUEVANAS…). The longest name has 12 letters — QUINTAMATERA itself.

Which bits select which piece

From chapter 1: the high seed bytes of location $37 are $BA $7E $93 $75. The type and order came from the first one. The name comes from the other three:

SEED+3 = $7E — the start and "is there a middle"

bit
7
6
5
4
3
2
1
0
SEED+3
0
1
1
1
1
1
1
0
$7E
AND #%00011111
0
0
0
1
1
1
1
1
$1F
= start
0
0
0
1
1
1
1
0
30 → QUINTA
SEED+3
0
1
1
1
1
1
1
0
$7E
AND #%00100000
0
0
1
0
0
0
0
0
$20
=
0
0
1
0
0
0
0
0
$20 not zero → Z = 0, BEQ does not branch: there is a middle

One mask keeps five bits (0–4), a number 0–31. The second mask keeps a single bit 5, and what matters there is not the number itself but "zero or not zero": AND sets the Z flag, and the BEQ @noMid right after it decides whether to skip the middle. Bit 5 is a coin toss: about half of the places have no middle.

SEED+5 = $93 and SEED+7 = $75 — the middle and the end

bit
7
6
5
4
3
2
1
0
SEED+5
1
0
0
1
0
0
1
1
$93
AND #%00011111
0
0
0
1
1
1
1
1
= middle
0
0
0
1
0
0
1
1
19 → MA
SEED+7
0
1
1
1
0
1
0
1
$75
AND #%00011111
0
0
0
1
1
1
1
1
= end
0
0
0
1
0
1
0
1
21 → TERA

QUINTA + MA + TERA = QUINTAMATERA. Exactly what the HUD shows in the game.

NAM_PRINT: the whole name

NAM_PRINT:
        LDA SEED+3              ; start: bits 0–4 of the S1 high byte
        AND #%00011111          ; n = 0–31
        JSR NAM_PART            ; print piece number A

        LDA SEED+3              ; is there a middle? bit 5 of the S1 high byte
        AND #%00100000
        BEQ @noMid              ; 0 — bit not set

        LDA SEED+5              ; middle: bits 0–4 of the S2 high byte, number 32 + n
        AND #%00011111
        ORA #%00100000          ; + 32
        JSR NAM_PART
@noMid:
        LDA SEED+7              ; end: bits 0–4 of the S3 high byte, number 64 + n
        AND #%00011111
        ORA #%01000000          ; + 64
        JSR NAM_PART
        RTS

NAM_PART takes a single number 0–95 and knows by itself which table to look in. That is why the middle becomes 32 + n and the end 64 + n. And this is done not with addition but with ORA:

ORA instead of addition: 19 → 51, 21 → 85

bit
7
6
5
4
3
2
1
0
A = 19
0
0
0
1
0
0
1
1
$13
ORA #%00100000
0
0
1
0
0
0
0
0
$20
= 51
0
0
1
1
0
0
1
1
$33 32 + 19
A = 21
0
0
0
1
0
1
0
1
$15
ORA #%01000000
0
1
0
0
0
0
0
0
$40
= 85
0
1
0
1
0
1
0
1
$55 64 + 21

After AND #%00011111, bits 5–7 are guaranteed to be zero. Setting an empty bit to 1 is the same as adding its weight: bit 5 weighs 32, bit 6 weighs 64. But ORA needs no CLC and does not touch the C flag. This is a common trick: when a bit is known to be free, "+ 32" is written as "set bit 5".

Where the syllables live: strings and an address table

All of this is in namedata.s, which is part of DATA and is moved into the hidden memory at startup (chapter 0). First come the syllables themselves, one after another, each made of letters with a 0 byte at the end. Here is QUINTA:

$E90AD1QNS30
$E90BD5U
$E90CC9I
$E90DCEN
$E90ED4T
$E90FC1A
$E91000end
$E911D2RNS31: RIVA

The syllables have different lengths, so "syllable number 30" cannot be found by multiplication. For that, three address tables follow the syllables: each holds 32 two-byte addresses — where each piece begins. The assembler fills in the label addresses itself:

NM_START:                  ; starts — $E9FA
        .word NS0, NS1, NS2 … NS31
NM_MID:                    ; middles — $EA3A = $E9FA + 64
        .word NM0, NM1 … NM31
NM_END:                    ; ends — $EA7A = $E9FA + 128
        .word NE0, NE1 … NE31

The tables sit back to back: 32 addresses × 2 bytes = 64 bytes, and the next table begins right after the previous one. So the three tables are really one table of 96 addresses. Numbers 0–31 land in the starts, 32–63 in the middles, 64–95 in the ends. That is what the "+ 32" and "+ 64" were for.

$EA360A#30 loNM_START+60
$EA37E9#30 hi→ $E90A QUINTA
…
$EA6050#51 loNM_START+102
$EA61E9#51 hi→ $E950 MA
…
$EAA4C9#85 loNM_START+170
$EAA5E9#85 hi→ $E9C9 TERA

NAM_PART: number → address → print

NAM_PART:
        ASL A               ; ×2 — 2-byte addresses (95 × 2 = 190, fits in X)
        TAX
        BIT LCRAM           ; the table is in the hidden memory
        LDA NM_START,X      ; low byte of the piece address
        STA STR
        LDA NM_START+1,X    ; high byte
        STA STR+1
        BIT LCROM
        JSR HUD_PUTS         ; print the string at address STR
        RTS
LineRegistersWhat happens (piece 30 — QUINTA)
ASL AA = 60 ($3C)Each address is 2 bytes, so the address of piece 30 starts at byte 60 of the table.
TAXX = $3CThe byte number goes into X to be used as an index.
BIT LCRAMThe hidden memory is switched in: $D000–$FFFF is now DATA, not ROM.
LDA NM_START,XA = $0AThe byte at $E9FA + $3C = $EA36.
STA STR$08 = $0A
LDA NM_START+1,XA = $E9The next byte, $EA37. NM_START+1 is the same trick as SEED+1: the assembler substitutes $E9FB itself.
STA STR+1$09 = $E9STR now holds the address $E90A — where "QUINTA" lives.
BIT LCROMROM is switched back: COUT comes next, and it lives in ROM.
JSR HUD_PUTSPrints the string at the address in STR — up to the 0 byte.

How many pieces can be set up this way? ASL A multiplies by 2 within a single byte: 95 × 2 = 190 — it fits. The limit is 128 pieces (127 × 2 = 254). Number 128 would give 256, which is no longer a byte: a 16-bit pointer would be needed, as in WLD_GET.

HUD_PUTS: printing a string from the hidden memory

HUD_PUTS:
        LDY #0
@loop:
        BIT LCRAM               ; the string may be in the hidden memory …
        LDA (STR),Y            ; character via the pointer
        BIT LCROM               ; … but COUT is in ROM
        CMP #0                  ; (BIT clobbered the Z flag)
        BEQ @done               ; 0 — end
        JSR COUT                ; COUT preserves Y
        INY
        BNE @loop
@done:
        RTS

The same loop as in LC_LOAD, but through a pointer: LDA (STR),Y takes the address from $08/$09 — $E90A — and adds Y. Two details here are easy to get wrong:

Where the name is printed: walk.s — the HUD at the bottom of the screen, mapview.s — the line under the map when the cursor is on a cell, market.s — the market heading. Everywhere it is the same: WLD_GET puts the seed of the required location into SEED, then JSR NAM_PRINT.

Chapter 3. A screen from a seed

A location is a square of 3 × 3 screens. A screen is 20 × 10 tile cells, each 14 × 16 pixels. Not a single cell is stored: when the hero enters a screen, the program rebuilds its map from the location seed and the screen number. The same screen always comes out identical, down to the tile.

Here are all nine screens of the starting location $37 as they appear in the game. The road runs through the seams: on screen 0 it leaves to the right and downward, and on screen 1 it continues. How the program keeps the screens in agreement, even though each one is built separately, is the main question of this chapter.

The nine screens of location QUINTAMATERA, 3 by 3
Location $37 QUINTAMATERA: screens 0–8. A level-6 town on screen 3, two industrial works on screens 1 and 4.

Two levels: location and screen

The work is split into two parts. One is done once on entering the location, the other on every screen.

WhenSubroutineWhat it decidesWhere it stores the result
entering a location
LOC_LOAD
LOC_ROLESwhich of the 9 screens hold the 3 settlementsLOC_ROLE, SET_SCR
LOC_SETTLkind and level of each settlementSET_KIND, SET_LVL
LOC_EXITSwhich neighbouring locations a road leads toGOUT
LOC_ROADSwhich seams between screens carry a roadGROAD (2 bytes)
+ LOC_GROWN (growth driven by the player, chapter 9) and SUB_LOC (substation, chapter 12)
every screen
SCR_GEN
GEN_SEEDinitialise this screen's random number generatorRND
GEN_SCREENbackground by terrain: 200 cellsSCR_MAP
GEN_ROADroad from the centre to the exitsSCR_MAP
GEN_SETTLsettlement buildings, as stamps placed by a templateSCR_MAP
GEN_POIone find in the surroundings: pharmacy, car, camp…SCR_MAP
SUB_GENthe substation yard, if this is its screenSCR_MAP

Everything that must match on neighbouring screens (roads through the seams) is decided on the first level, for the whole location at once. Screen 0 and screen 1, built at different times, then read the same seam table and cannot disagree.

The result of the second level is SCR_MAP: 200 bytes at $0800, one tile number per cell, row by row. Cell number = row × 20 + column. Drawing (chapter 4) simply walks these 200 numbers and draws the picture of each tile. Here is SCR_MAP for screen 4:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
0
6
49
49
49
49
49
1
1
6
7
21
6
7
49
49
49
49
49
1
1
1
1
50
50
50
50
50
6
66
6
1
21
1
1
50
50
50
50
50
1
1
2
1
50
50
51
50
50
1
1
1
1
21
6
7
50
50
51
50
50
1
1
3
1
1
1
97
1
1
1
1
1
1
21
1
1
7
1
97
6
7
1
6
4
26
26
26
26
26
26
26
26
26
26
25
1
1
1
1
7
1
1
1
1
5
6
49
49
49
49
49
1
1
1
1
1
7
1
6
7
1
6
6
1
1
6
7
50
50
50
50
50
1
52
52
7
1
1
1
52
52
1
66
66
1
1
7
1
50
50
51
50
50
1
52
52
1
1
1
1
52
52
1
66
1
1
1
8
7
1
1
97
1
1
7
1
6
6
1
1
1
6
6
6
7
1
1
1
9
1
1
1
1
1
1
1
1
1
1
1
1
1
6
56
57
7
1
6
6
0–15 nature16–31 roads32–63 buildings64–79 ruins80–95 machinery96–111 paths
Screen 4: industrial works, road at the top and on the left
The same screen 4 on the monitor. 1 — dry ground, 6 — rocks, 7 — cliff (the "rocky" terrain), 49 / 50 / 51 — factory: saw-tooth roof, walls, gate; 52 — tanks, 56 57 — truck, 66 — rubble, 21 / 25 / 26 — road, 97 — path from the gate. Cell 90 (row 4, column 10) is the centre; every road passes through it.

LOC_ROLES: where the settlements stand

Every location has exactly three settlements, and each needs a screen 0–8. The low bytes of the seed are used, the very ones that "repeat quickly" (chapter 1). To rescue them, each is mixed with the high byte of the next word using EOR:

        TXA                     ; X = settlement 0, 1, 2
        ASL A
        TAY                     ; Y = 0, 2, 4
        LDA SEED,Y              ; low byte of the word
        EOR SEED+3,Y            ; × high byte of the next one
        LSR A                   ; top 4 bits → 0–15
        LSR A
        LSR A
        LSR A
        CMP #9
        BCC @scr                ; 0–8 — done
        SEC
        SBC #9                  ; 9–15 → 0–6

Seed $37 in memory: $42 $BA $80 $7E $A3 $93 $86 $75. Settlement 1 (Y = 0) uses bytes SEED+0 and SEED+3:

EOR: $42 × $7E → screen 3

bit
7
6
5
4
3
2
1
0
SEED+0
0
1
0
0
0
0
1
0
$42
EOR SEED+3
0
1
1
1
1
1
1
0
$7E
= A
0
0
1
1
1
1
0
0
$3C
4 × LSR
0
0
0
0
0
0
1
1
3 top 4 bits → 0–15; 3 < 9 → screen 3

EOR is "exclusive OR": the result has 1 where the bits are different. It is the third logical instruction alongside AND and ORA from chapter 0. Its key property is that it loses nothing: every result bit depends on both bytes. That makes it a good tool for "mixing two numbers".

Settlement 3: $A3 × $75 → 13 → screen 4

bit
7
6
5
4
3
2
1
0
SEED+4
1
0
1
0
0
0
1
1
$A3
EOR SEED+7
0
1
1
1
0
1
0
1
$75
= A
1
1
0
1
0
1
1
0
$D6
4 × LSR
0
0
0
0
1
1
0
1
13 13 ≥ 9
SBC #9
0
0
0
0
0
1
0
0
4 → screen 4

Four bits give 0–15, but there are only 9 screens. The numbers 9–15 "wrap around": subtract 9 to get 0–6. SBC is preceded by SEC, the mirror of CLC before ADC: in subtraction the carry flag means "no borrow", and it must be set to 1, otherwise an extra 1 is subtracted.

Settlement 2: $80 × $93 = $13 → 1 → screen 1. In total: settlement 1 on screen 3, settlement 2 on screen 1, settlement 3 on screen 4. Exactly as in the picture.

What if two settlements land on the same screen? The @busy loop handles that: if the screen's LOC_ROLE is already non-zero, the next screen is tried, wrapping from 8 back to 0. A free screen always exists: three settlements, nine screens.

LOC_SETTL: kind and level

The kind depends only on the location type, via the table KIND_TAB, one row per type:

KIND_TAB:                       ; settlement 1, 2, 3, spare
        .byte 3, 3, 3, 0        ; 0 anarchy:    camp × 3
        .byte 0, 0, 0, 0        ; 1 rural:      village × 3
        .byte 1, 2, 2, 0        ; 2 industrial: town + works × 2   ← $37
        .byte 1, 0, 0, 0        ; 3 developed:  town + village × 2

A table row is 4 bytes, so the row offset = type × 4 (ASL ASL), and the byte = type × 4 + settlement number. The fourth "spare" byte is not needed, but with it a row is exactly 4 bytes, so the multiplication is a shift rather than additions for × 3.

Level = order / 2 + two more bits of the same mixed byte (bits 2–3). For $37 the order is 6, so the base is 3:

SettlementEOR byteBits 2–3LevelIn the game
1 (screen 3)$3C = 0011 110011 = 33 + 3 = 6SETTLEMENT 1 TOWN LV 6
2 (screen 1)$13 = 0001 001100 = 03 + 0 = 3SETTLEMENT 2 WORKS LV 3
3 (screen 4)$D6 = 1101 011001 = 13 + 1 = 4SETTLEMENT 3 WORKS LV 4

One seed byte works twice: bits 4–7 decide where the settlement is, bits 2–3 how developed it is. This squeezes more properties out of 64 bits.

LOC_EXITS: a road to the neighbouring location

Is there a road from $37 up to $27? The decision must be made so that both locations give the same answer: if a road leaves $37 upward, it must arrive in $27 from below. Otherwise the hero would follow the road and end up in a field.

The solution: EOR the same seed byte of both locations. For vertical neighbours it is byte 5, for horizontal ones byte 7. If the two low bits come out 00, there is no road (1 case in 4); otherwise there is.

$37 ↑ $27: neighbour byte 5 × own byte 5

bit
7
6
5
4
3
2
1
0
$27: SEED+5
0
1
1
1
1
0
0
1
$79
EOR $37: SEED+5
1
0
0
1
0
0
1
1
$93
= A
1
1
1
0
1
0
1
0
$EA
AND #%11
0
0
0
0
0
0
1
0
2 not 0 → there is an exit upward, GOUT = 1

The trick is that EOR does not care about order: $79 EOR $93 = $93 EOR $79. When the game builds $27 and asks about the neighbour below, it computes the same $EA and also answers "there is a road". Agreement without storage.

For $37 the other three pairs give 00: down $0B × $93 = $98, right $95 × $75 = $E0, left $A9 × $75 = $DC; all have low bits 00. Result: GOUT = 1, the only exit is upward. An exit to a neighbour is always on the middle screen of that side: up — screen 1, right — 5, down — 7, left — 3 (table OUT_SCR).

LOC_ROADS: L-shaped roads and seams

Roads inside a location link the settlements in a chain 1 → 2 → 3, and every exit to a neighbour is linked to settlement 1. The path from screen to screen is L-shaped: first along the row to the required column, then along the column (ROAD_PATH). Each step switches on a seam between two screens.

A 3 × 3 square has twelve seams: 6 horizontal (between screens in a row) and 6 vertical. All of them are kept in two bytes, GROAD: byte 0 for horizontal seams, byte 1 for vertical ones, one bit per seam. For $37, GROAD = $05, $03:

0
b0·0
1settl. 2
b0·1
2
b1·0
b1·1
b1·2
3settl. 1
b0·2
4settl. 3
b0·3
5
b1·3
b1·4
b1·5
6
b0·4
7
b0·5
8

1 → 2 (screen 3 → 1): column 0 → 1, a step right, seam 3–4 (b0·2). Then screen 4 → 1 upward, seam 1–4 (b1·1).

2 → 3 (screen 1 → 4): same column, downward, seam 1–4, already on.

Exit ↑ (screen 1 → settlement 1 on screen 3): left, seam 0–1 (b0·0); down, seam 0–3 (b1·0).

Byte 0 = %00000101 = $05, byte 1 = %00000011 = $03.

A seam is switched on with a single ORA, using a bit from the table RD_SIDES, which records for every screen and every side which GROAD byte holds its seam and which bit. Setting a bit that is already set does no harm: ORA breaks nothing. So paths 1 → 2 and 2 → 3 can safely share a seam.

Moving to the neighbouring screen is an addition from the table STEP_D: ↑ −3, → +1, ↓ +3, ← −1. A byte has no minus sign, so the table holds 253, 1, 3, 255: 1 + 255 = 256 = 0 in a byte, the same as 1 − 1. This is "subtraction by wrap-around addition", the same counter rolled through zero as in CMP from chapter 0.

GEN_EXITS: which sides this screen has

When a particular screen is built, GEN_EXITS looks up its four seams in GROAD and builds the mask GEXIT: ↑ = 1, → = 2, ↓ = 4, ← = 8. Plus the exit to the neighbouring location, if the screen is the middle one on an edge (OUT_MASK).

ScreenSeamsGEXITBits ←↓→↑
0→ 0–1, ↓ 0–32 + 4 = 60110
1↑ exit to $27, ↓ 1–4, ← 0–11 + 4 + 8 = 131101
3↑ 0–3, → 3–41 + 2 = 30011
4↑ 1–4, ← 3–41 + 8 = 91001
2, 5, 6, 7, 8—00000

The numbers follow directly from the seams, and in the game the screens come out exactly like this.

GEN_ROAD: the road on a screen

The road always passes through the centre, cell 90 (row 4, column 10). It gets tile 16 + GEXIT: numbers 16–31 are exactly 16 road tile variants, one per mask. On screen 4 GEXIT = 9, and the centre holds tile 25, the "┘" bend, up and left. The tile number itself tells where it leads.

Next come the straight pieces: if there is →, cells 91–99 get tile "─" (16 + 2 + 8 = 26); if ↑, cells 10, 30, 50, 70 get tile "│" (16 + 1 + 4 = 21). The vertical run steps by 20, one row down:

        LDX #10                 ; ↑ : cells 10, 30, 50, 70
@u:
        LDA #T_ROAD0+5          ; │ (↑1 + ↓4)
        STA SCR_MAP,X
        TXA
        CLC
        ADC #20                 ; X + 20: next row
        TAX
        CPX #90                 ; up to the centre
        BNE @u

The 6502 cannot add to X directly, only INX by 1. So X is moved to A (TXA), 20 is added, and the result is moved back (TAX). The SCR_MAP of screen 4 shows exactly this: column 10, rows 0–3 hold 21, row 4 on the left holds 26, the centre holds 25.

GEN_SEED and GEN_RND: a screen's randomness

Rocks, bushes and trees are scattered "randomly", but the randomness must be the same on every visit. For that, each screen has its own generator. GEN_SEED initialises it from the screen number and two bytes of the location seed:

        LDA GSCR                ; screen number × 17
        ASL A                   ; ×2
        ASL A                   ; ×4
        ASL A                   ; ×8
        ASL A                   ; ×16
        CLC
        ADC GSCR                ; ×16 + ×1 = ×17
        EOR SEED+5              ; mix with the location seed
        CLC
        ADC SEED+7

Screen 4: 4 × 17 = 68 = $44; $44 EOR $93 = $D7; $D7 + $75 = $14C → $4C in a byte. Multiplying by 17 makes neighbouring screens (4 and 5) produce very different numbers rather than numbers one apart.

The generator itself is GEN_RND, six instructions. It is a "linear feedback shift register": shift the byte left, and if a 1 falls out, flip several bits:

GEN_RND:
        LDA RND
        ASL A                   ; shift left, bit 7 → C
        BCC @nox                ; a 0 fell out — leave as is
        EOR #$1D                ; a 1 fell out — flip bits 0, 2, 3, 4
@nox:
        STA RND
        RTS

One step: $8F → $03 (first cell of screen 4)

bit
7
6
5
4
3
2
1
0
RND
1
0
0
0
1
1
1
1
$8F
ASL A
0
0
0
1
1
1
1
0
$1E bit 7 (1) falls into C → C = 1
EOR #$1D
0
0
0
1
1
1
0
1
$1D
= RND
0
0
0
0
0
0
1
1
$03

After 8 idle "warm-up" steps RND = $8F, and the first real step gives $03. Then: $06, $0C, $18, $30, $60… until a 1 falls out again. Such a generator runs through every number 1–255 exactly once and only then repeats. Zero is forbidden: it would never leave zero (0 shifted is still 0), so GEN_SEED contains a check "if 0, use 1".

Here BCC looks not at a comparison but at the bit that has just fallen out of ASL. The carry flag is one and the same for carry, comparison and shifts.

Why the mask is $1D: bits 0, 2, 3, 4

If the generator only shifted, after 8 steps the byte would become zero and stay there. EOR with the mask "returns" the 1 that fell out into several places on the right. Which places determines how many different numbers the generator visits before it starts repeating. Here is the same start, 1, with different masks:

MaskBitsNumbers before repeatEffect on a 200-cell screen
$010000 00018the pattern repeats every 8 cells
$110001 000112every 12
$050000 010130every 30, a row and a half
$1B0001 101151every 51
$0F0000 1111217almost good, but not all numbers
$FF1111 11119every 9
$1D0001 1101255all numbers 1–255, repeat only after 255 cells

With mask $05 the generator returns to the start after 30 steps, and everything after that goes round in a circle:

0102040810204080050A142850A0458A11224488152A54A855AA51A2418201

With mask $1D it returns after 255, having visited every number from 1 to 255 exactly once:

01020408102040801D3A74E8CD8713264C982D5AB475EAC98F03060C183060C09D274E9C… 219 more01

Of the 255 possible masks only 16 give the full cycle: $1D $2B $2D $4D $5F $63 $65 $69 $71 $87 $8D $A9 $C3 $CF $E7 $F5. $1D is the smallest of them. There is no need to search for it by trial: this is the mathematics of polynomials over bits ("finite fields"), and such masks were computed long ago and listed in tables. Mask $1D together with the ninth bit that falls out is the polynomial x⁸ + x⁴ + x³ + x² + 1. The same one is used in QR codes, in their error-correction code, and in one of the common CRC-8 checksums.

For the game this means: a screen needs 200 random numbers, and repetition starts only after 255, so no pattern is visible. With mask $05, rocks and bushes would form identical "patches" every 30 cells.

GEN_SCREEN: background by terrain

Terrain is bits 5–7 of the high byte of S0 (chapter 1). For $37 it is 5, "rocky". For every terrain the table RLF_TAB has an 8-byte row: background, threshold 1, tile 1, threshold 2, tile 2.

RLF_TAB:   ; backgr.  thresh 1  tile 1     thresh 2  tile 2
        .byte T_GRASS, 25, T_TREE, 40, T_BUSH, 0, 0, 0          ; 0 meadow
        ...
        .byte T_DRY, 55, T_ROCKS, 80, T_CLIFF, 0, 0, 0           ; 5 rocky   ← $37
        ...
        .byte T_SAND, 15, T_BUSH, 28, T_ROCKS, 0, 0, 0          ; 7 coast

Each of the 200 cells gets a new generator number 1–255. Below 55 means rocks, 55 to 79 a cliff, anything else dry ground. So rocks cover about 54 / 255 ≈ 21 %, cliffs ≈ 10 %, dry ground ≈ 69 %. The thresholds are the "character" of the terrain: in a forest (4) trees exceed 40 %.

Finding the terrain row: AND and two LSRs

bit
7
6
5
4
3
2
1
0
SEED+1
1
0
1
1
1
0
1
0
$BA
AND #%11100000
1
1
1
0
0
0
0
0
$E0
= A
1
0
1
0
0
0
0
0
$A0 terrain 5 sits "in place × 32"
LSR A ×2
0
0
1
0
1
0
0
0
$28 = 40 = 5 × 8, start of row 5 in the table

The trick: bits 5–7 already mean "terrain × 32". What is needed is "terrain × 8" (rows of 8 bytes). Instead of three shifts right and three left, two shifts right: × 32 / 4 = × 8. That is why the table rows are 8 bytes long even though only five are useful.

@cell:
        JSR GEN_RND             ; A = 1–255
        CMP RLF_TAB+1,Y         ; below threshold 1?
        BCS @not1               ; A ≥ threshold — no
        LDA RLF_TAB+2,Y         ; tile 1
        JMP @put
        ...
@put:
        STA SCR_MAP,X
        INX
        CPX #200
        BNE @cell

Cell 0 of screen 4: the generator gives $03 = 3; CMP #55: 3 < 55, C = 0, BCS does not branch, so tile 1, rocks (6). In SCR_MAP cell 0 is indeed 6. Both index Y (terrain row) and X (cell) are in use here: GEN_RND is deliberately written so that it touches neither X nor Y.

GEN_STAMP and GEN_SETTL: buildings as stamps

A building is not one tile but several: roof, walls, door. Such a group is called a stamp: width, height and tile numbers row by row. The works' factory:

ST_FACTORY:
        .byte 5, 4                                              ; 5 × 4 cells
        .byte T_SAW_ROOF, T_SAW_ROOF, T_SAW_ROOF, T_SAW_ROOF, T_SAW_ROOF      ; 49 × 5
        .byte T_METAL_WALL, T_METAL_WALL, T_METAL_WALL, T_METAL_WALL, T_METAL_WALL  ; 50 × 5
        .byte T_METAL_WALL, T_METAL_WALL, T_GATE, T_METAL_WALL, T_METAL_WALL  ; gate 51
        .byte ST_SKIP, ST_SKIP, T_PATH_DOOR, ST_SKIP, ST_SKIP              ; path 97

ST_SKIP ($FF) means "leave alone": the background stays there. So the path from the gate is laid on its own, with rocks on either side. The factory is visible in the screen 4 grid: rows 0–3, columns 1–5.

The placement is the cell "row × 20 + column". Multiplying by 20 without a multiply instruction: 20 = 16 + 4.

GEN_STAMP: row 4 × 20 = (4 × 4) + (4 × 16)

bit
7
6
5
4
3
2
1
0
A = row
0
0
0
0
0
1
0
0
4
ASL ASL → GTMP
0
0
0
1
0
0
0
0
16 × 4, saved
ASL ASL
0
1
0
0
0
0
0
0
64 × 16
ADC GTMP
0
0
0
1
0
0
0
0
16
= A
0
1
0
1
0
0
0
0
80 × 20; + column 10 → cell 90

Any multiplication by a constant is done this way: split the constant into powers of two (20 = 16 + 4), get each part with shifts, and add them. Four shifts and one addition, faster than any loop.

Which stamps to place is decided by the settlement's template: a list of 4-byte slots — column, row, minimum level, stamp number. The works template:

TPL_WORKS:                      ; column, row, level, stamp
        .byte 1, 0, 0, S_FACTORY      ; ✓ 4 ≥ 0   factory top left
        .byte 14, 9, 0, S_TRUCK       ; ✓ 4 ≥ 0   truck 56 57
        .byte 13, 0, 1, S_FACTORY     ; ✓ 4 ≥ 1   factory top right
        .byte 7, 6, 2, S_TANKS        ; ✓ 4 ≥ 2   tanks 52
        .byte 1, 5, 3, S_FACTORY      ; ✓ 4 ≥ 3   factory bottom left
        .byte 13, 6, 4, S_TANKS       ; ✓ 4 ≥ 4   tanks
        .byte 16, 6, 5, S_TANKS       ; ✗ 4 < 5   → ruins: rubble 66 66
        .byte 7, 1, 6, S_GEN         ; ✗ 4 < 6   → ruins: rubble 66
        .byte $FF                     ; end

Settlement 3 on screen 4 is level 4. GEN_SETTL walks the slots and compares: CMP GSL / BCS @whole — "level ≥ threshold: an intact building". Otherwise it takes the same stamp number from the ruin table ST_RUIN. This way a growing settlement (chapter 9) "rebuilds itself": once its level rises to 5, tanks appear in place of the rubble in columns 16–17. Nothing is stored except a single number, the level.

The template keeps row 4 and column 10 free, since roads run along them. So a building never stands across a road.

Chapter 4. How HiRes is drawn

In chapter 3 the screen became 200 tile numbers — SCR_MAP. Now those numbers have to become pixels on the monitor. That requires knowing how the Apple II stores a picture, and it stores it in a very unusual way. HiRes has three oddities: 7 pixels per byte, in reverse order; the colour depends on which column a pixel is in; and the screen lines are scattered through memory out of order.

The screen is 8 KB of memory

HiRes is 280 × 192 pixels. Page 1 is memory $2000–$3FFF, page 2 is $4000–$5FFF, 8,192 bytes each. There is no video card: the Apple's video circuitry reads this memory 60 times a second and displays whatever is there. Writing a byte to an address in this range changes the pixels on screen immediately.

A line is 40 bytes. 40 × 8 = 320, yet a line has 280 pixels, because only 7 bits of each byte, 0–6, reach the screen. Bit 7 is not a pixel: it selects the "colour pair" for all seven pixels of that byte.

Byte $2A — seven pixels and a colour bit

bit
7
6
5
4
3
2
1
0
$2A
0
0
1
0
1
0
1
0

Most importantly, bit 0 is the leftmost pixel and bit 6 the rightmost. Diagrams always draw bit 7 on the left, so on screen a byte appears "backwards": $2A = 0010 1010 lights up as .#.#.#. — pixels 1, 3, 5. In the tile sources each byte is accompanied by exactly this picture, already in screen order:

TL_TREE:          ; 3: tree
        .byte $00, $00  ; .......|.......
        .byte $20, $01  ; .....#.|#......
        .byte $28, $05  ; ...#.#.|#.#....
        .byte $28, $15  ; ...#.#.|#.#.#..
        .byte $2A, $15  ; .#.#.#.|#.#.#..
        ...
        .byte $A0, $81  ; .....#.|#......   ← trunk: bit 7 = 1
        ...

A tile is 14 × 16 pixels: 2 bytes wide, 16 lines, 32 bytes in total. 14 pixels = exactly 2 bytes of 7, so tiles fit the grid with no shifting: 20 tiles × 2 bytes = 40 bytes = a whole line.

Where colour comes from

The Apple II does not "store" colour. Colour results from which column a single lit pixel is in and what bit 7 of its byte is. It is a trick with the NTSC television signal, devised by Wozniak to avoid separate colour memory:

PixelEven columnOdd column
single, bit 7 = 0 violet green
single, bit 7 = 1 blue orange
two adjacent white
off black

That is why the tree's green crown is drawn "every other pixel" — pixels only in odd columns — while the trunk is also in odd columns but in bytes with bit 7 = 1, so it turns orange. Here are line 4 of the crown and line 10 of the trunk:

012345678910111213
01010101010100
line 4: $2A $15 — pixels in columns 1, 3, 5, 7, 9, 11 (all odd), bit 7 = 0 → green
012345678910111213
00000101000000
line 10: $A0 $81 — pixels 5 and 7, bit 7 = 1 → orange

And here is the whole tile computed by these rules — exactly as it appears in the game:

0$00 $00
1$20 $01
2$28 $05
3$28 $15
4$2A $15
5$2A $15
6$2A $15
7$28 $15
8$28 $05
9$28 $05
10$A0 $81
11$80 $81
12$80 $81
13$80 $81
14$A0 $81
15$00 $00

On the left is the line number, on the right its two bytes. The black stripe in the middle is the byte boundary: columns 0–6 come from the first byte, 7–13 from the second.

This limitation shows in every Apple II game: green and orange cannot be mixed within one byte, because there is one bit 7 for seven pixels. The tiles are drawn with this in mind: each group of 7 pixels belongs to one "pair".

White is two adjacent pixels. Rocks, walls and houses in the game are white precisely because they are drawn with solid lines.

Lines are laid out in memory like a staircase

The strangest part. The logical layout would be: line 0 at $2000, line 1 at $2028 (40 bytes later), line 2 at $2050… But no. On the Apple II a line address is made of three parts:

address = $2000 + (y mod 8) × $400 + ((y / 8) mod 8) × $80 + (y / 64) × $28
Line yy mod 8 (× $400)band (× $80)block (× $28)Address
0000$2000
1100$2400
2200$2800
7700$3C00
8010$2080
9110$2480
63770$3F80
64001$2028
128002$2050
191772$3FD0

Adjacent lines are $400 = 1,024 bytes apart. Only 8 lines later does the address move by $80. The screen is divided into 3 blocks of 64 lines, each block into 8 "bands" of 8 lines. Wozniak arranged it so that one and the same counter in the video circuitry served both text and graphics and refreshed the memory at the same time. That saved a few chips — and left programmers with the staircase forever.

It also explains why a title picture loaded with BLOAD straight into video memory "develops" like venetian blinds: the file is written to memory sequentially, and sequential memory holds lines 0, 64, 128, then 8, 72, 136, 16… — one line in each band, and only then lines 1, 9, 17…

SCR_ROWS: a table instead of a formula

Evaluating the formula for every line of every tile is expensive. So at startup SCR_ROWS fills two 192-byte tables once: ROW_LO ($1C00) holds the low byte of each line address, ROW_HI ($1CC0) the high byte. After that, the address of any line takes two reads: LDA ROW_LO,X and LDA ROW_HI,X.

Inside are three nested loops — block, band, line — and a trick: +$400 is +4 to the high byte, the low byte does not change. So the 8 lines of a band share the same low byte while the high byte grows by 4:

@line:
        LDA SBASE               ; low byte is the same for all 8 lines of the band
        STA ROW_LO,Y
        LDA SHI
        STA ROW_HI,Y
        CLC                     ; next line: +$400 = high byte +4
        ADC #4
        STA SHI
        INY
        INX
        CPX #8
        BNE @line

Lines 0–7: low byte $00, high byte $20, $24, $28 … $3C. Then the band adds $80 (lines 8–15: $2080, $2480…), and after 8 bands the block adds $28. The end of a band is detected cleverly: TYA / AND #%00111111 / BNE @band — "is the line number divisible by 64?". The mask keeps the 6 low bits; if they are all zero, the block is finished.

SCR_TILE: a tile into a cell

Drawing a tile into a cell (column X, row Y of the 20 × 10 grid) means copying 2 bytes to the right places on screen 16 times. Example: the middle of a road, the cell at column 10, row 4:

SCR_TILE:
        BIT LCRAM               ; tile images live in the language card
        TXA                     ; byte within line = column × 2
        ASL A                   ; 10 → 20
        STA TCOL
        TYA                     ; first pixel line = cell row × 16
        ASL A
        ASL A
        ASL A
        ASL A                   ; 4 → 64
        STA TLINE
        LDA #16
        STA TCNT                ; 16 pixel lines
@row:
        LDX TLINE
        CLC
        LDA ROW_LO,X            ; address of line 64 — low byte
        ADC TCOL                ; + 20 bytes to the right
        STA PTR
        LDA ROW_HI,X            ; high byte
        ADC DPAGE               ; + $00 (page 1) or + $20 (page 2)
        STA PTR+1
        LDY #0
        LDA (TILEP),Y          ; image byte …
        STA (PTR),Y            ; … to the screen
        INY
        LDA (TILEP),Y          ; second byte
        STA (PTR),Y
        ...                     ; TILEP + 2, TLINE + 1, TCNT − 1
StepNumbersWhat happens
TCOL10 × 2 = 20A tile is 2 bytes wide, so cell 10 starts at byte 20 of the line.
TLINE4 × 16 = 64Cell row 4 starts at pixel line 64 — the start of the second block.
ROW(64)$2028From the table: ROW_LO = $28, ROW_HI = $20.
+ TCOL$203C$28 + 20 ($14) = $3C. No carry, the high byte stays $20.
+ DPAGE$203C / $403CWhen drawing on page 2, DPAGE = $20, and $20 + $20 = $40. The whole second page is the same staircase, just $2000 further on.
line 65$243CThe next line of the tile is $400 further on.

A neat detail: STA (PTR),Y and LDA (TILEP),Y use the same Y = 0, 1. Two pointers, one counter — the left byte of the tile goes to the left byte of the cell, the right byte to the right one.

DPAGE is what makes drawing on the hidden page possible: there is one subroutine, and a single variable decides where it writes. How this is used against flicker is covered in chapter 5.

SCR_TILEN and SCR_DRAW: from number to image

SCR_TILE takes an image address as input, while SCR_MAP holds numbers. SCR_TILEN does the translation through the address table TILE_TAB ($DC00), with the same technique as the syllables in chapter 2: number × 2 → two address bytes.

$DC0640TILE_TAB+6tile 3 lo
$DC07DDTILE_TAB+7tile 3 hi
→
$DD4000TL_TREEline 0
$DD4100
$DD4220line 1.....#.
$DD4301#......
SCR_TILEN:
        BIT LCRAM
        STX TCX                 ; X and Y are still needed — save the cell
        STY TCY
        ASL A                   ; tile number × 2
        TAX
        LDA TILE_TAB,X
        STA TILEP
        LDA TILE_TAB+1,X
        STA TILEP+1
        LDX TCX                 ; restore the cell
        LDY TCY
        JMP SCR_TILE            ; "tail call"

Tail call. Instead of JSR SCR_TILE + RTS there is JMP SCR_TILE. SCR_TILE ends with its own RTS, which returns to wherever SCR_TILEN was called from, because that is exactly the return address on the stack. The saving: one byte of code, 9 cycles and two bytes of stack. The technique appears often in the game — note the JMP at the end of many subroutines.

Why X and Y must be saved. There are only three registers, and TAX takes X for the table index. The cell is parked in memory for a while (TCX, TCY) and fetched back later. This is constant work on the 6502: registers are the "hands", memory is the "pockets".

SCR_DRAW is just two nested loops, 10 rows × 20 cells: take a number from SCR_MAP and call SCR_TILEN. Counting cycles, one tile takes about 1,600 cycles and the whole screen about a third of a second at 1 MHz. Drawn on the visible page, this is noticeable to the eye: the screen "fills in" from top to bottom. That is why a new screen is drawn on the hidden page and shown all at once.

Chapter 5. The hero

The tiles of chapter 4 sit in the grid exactly on byte boundaries: a cell = 2 bytes. The hero cannot do that — he moves 2 pixels at a time, and a byte holds 7. So the figure almost always starts somewhere in the middle of a byte and spans three bytes at once. On top of that, it has to be drawn over grass and rocks without wiping them out with a rectangle, and without flicker. This chapter covers three tricks: shift tables, a mask and two pages.

Where the hero stands: HX2 and HY

The position is two bytes: HY is the pixel line of the top edge (0–144), HX2 is the column divided by 2 (0–132). Why halved? The screen is 280 pixels wide, but a byte holds only 0–255. Half of that, 0–140, fits. Besides, the hero's step is 2 pixels anyway, so x is always even: columns never change parity, and the figure's coloured pixels do not "shimmer" from green to violet while walking (chapter 4).

The figure is 14 × 16 pixels, like a tile. Drawing it at pixel x requires two numbers: which byte of the line it starts in and how many pixels it is shifted within that byte: x = byte × 7 + shift. The processor cannot divide by 7, so at startup HERO_PREP builds two tables covering all 140 positions: XB_TAB (byte) and XS_TAB (shift 0–6).

@xt:                            ; X = HX2 = 0, 1, 2 …
        LDA HB
        STA XB_TAB,X
        LDA HS
        STA XS_TAB,X
        LDA HS                  ; next x — 2 pixels to the right
        CLC
        ADC #2
        CMP #7                  ; past the end of the byte?
        BCC @xn
        SBC #7                  ; (C = 1 after CMP — the subtraction is exact)
        INC HB                  ; next byte
@xn:
        STA HS
HX2xXB_TAB (byte)XS_TAB (shift)How it was computed
0000start
12020 + 2
36064 + 2
48116 + 2 = 8 ≥ 7 → 8 − 7 = 1, byte + 1
20405540 = 5 × 7 + 5

Once again, "division without division": instead of x / 7, the table is built by adding 2 at a time and carrying into the next byte — like counting on an abacus. A small detail: SBC #7 without SEC. It is not needed, because right before it CMP #7 has already set C = 1 (A ≥ 7, otherwise BCC would have branched).

Shifting the figure: 2 bytes → 3 bytes

Example: line 8 of the "hero from behind" frame: $4C, $19 — ·.##..##..##.·. The hero stands at HX2 = 20: byte 5, shift 5. On screen his 14 pixels must start at pixel 5 of byte 5 — that is, spread across three bytes:

source line: $4C $19 — pixels 2, 3, 6, 7, 10, 11 (14 pixels = 2 bytes)
after a shift of 5: pixels 7, 8, 11, 12, 15, 16 → three bytes $00 $33 $06

An important source of confusion worth remembering: a shift to the right on screen is a shift to the left in the byte. Bit 0 is the leftmost pixel (chapter 4), so for a pixel to move right its bit must become more significant: ASL, not LSR.

Shifting every byte of every line in a loop on every frame is slow. So HERO_PREP builds 7 shift tables in advance, one page for each shift s = 0–6 (SHTAB, $1500–$1BFF). Each page has two halves:

[v]       = (v << s) AND $7F     ; what stays in this byte
[v + 128] = (v << s) >> 7       ; what moves into the next byte

Byte $4C, shift 5: what stays and what moves

bit
7
6
5
4
3
2
1
0
v
0
1
0
0
1
1
0
0
$4C
v << 5: hi
0
0
0
0
1
0
0
1
$09 16 bits: $4C × 32 = $0980
v << 5: lo
1
0
0
0
0
0
0
0
$80
stays
0
0
0
0
0
0
0
0
$00 low 7 bits — not a single pixel
moves
0
0
0
1
0
0
1
1
$13 everything past bit 6, shifted right by 7

In the table in memory, "stays" is at address $1500 + 5 × 256 + $4C = $1A4C, "moves" at $1ACC (+ 128). It is built with the same ASL WORK / ROL WORK+1 as the multiplication by 8 in chapter 1: a 16-bit shift through the carry.

Now SHIFT3 assembles three bytes from two — a single formula:

OUT0 = stays(b0)                       ; = $00
OUT1 = moves(b0) OR stays(b1)          ; = $13 OR $20 = $33
OUT2 = moves(b1)                       ; = $06

OUT1: tail of the first byte + head of the second

bit
7
6
5
4
3
2
1
0
moves($4C)
0
0
0
1
0
0
1
1
$13
ORA stays($19)
0
0
1
0
0
0
0
0
$20
= OUT1
0
0
1
1
0
0
1
1
$33 screen pixels 7, 8, 11, 12 — in byte 6

The two halves do not overlap (one occupies bits 0–4, the other bits 5–6), so ORA simply glues them together. The result, $00 $33 $06, is exactly what the pixel strip above shows. The whole job for one line is four table reads and one ORA, without a single shift.

The mask: drawing on top without erasing the background

Simply writing the hero's bytes to the screen would leave a black rectangle around him — the background pixels where the hero is "empty" would go dark. So every line of a frame also has a mask: 1 means "transparent here, keep the background", 0 means "the hero is here". Drawing is one line of logic per byte:

screen = (screen AND mask) OR image
@byte:
        LDA (PTR),Y              ; what is on screen now
        AND (MPTR),Y             ; turn off pixels where the hero is
        ORA (HPTR),Y             ; turn on the hero's pixels
        STA (PTR),Y
        INY
        CPY #3                    ; 3 bytes per line
        BNE @byte

One screen byte: background $88, mask $81, hero $4C (no shift)

bit
7
6
5
4
3
2
1
0
screen (dry grass)
1
0
0
0
1
0
0
0
$88 one grass pixel (3) and the background bit 7
AND mask
1
0
0
0
0
0
0
1
$81 1 = transparent: pixel 0 and bit 7
=
1
0
0
0
0
0
0
0
$80 the grass pixel under the hero went dark, bit 7 remains
ORA image
0
1
0
0
1
1
0
0
$4C
= screen
1
1
0
0
1
1
0
0
$CC hero on top, pixel 0 from the background

The mask always has bit 7 = 1: the colour pair of the byte comes from the background. Otherwise, wherever the hero walks over orange ground, bits of background in the same byte would change colour. The hero's outline is zeros in the mask and zeros in the image: those pixels go dark, producing a thin black border that separates the white figure from white rocks.

The mask has to be shifted too — and there is a trap. A shift fills the vacated bits with zeros, and 0 in the mask means "the hero is here". A black band would appear around the shifted figure. So PREP_ROW first inverts the mask (EOR #%01111111 — now 1 = "the hero is here"), shifts this "hero shadow" through the same tables, where zeros do mean "empty", and only then inverts it back — EOR #%11111111, setting bit 7 = 1 at the same time.

EOR with ones means "flip the bits". Earlier, EOR appeared as "mix" (chapter 3) and "flip some of the bits" (the generator). Here it plays a third role: NOT for selected bits.

Mirroring: left = right reflected

A character has 6 frames: three views (↑, →, ↓) × two steps. There is no "left" view — it is "right" mirrored. Mirroring a 14-pixel line means swapping the two bytes and reversing the order of the 7 pixels in each. The latter uses the 128-entry table REV7:

REV7: $0C → $18 (pixels 2, 3 → pixels 4, 3)

bit
7
6
5
4
3
2
1
0
v
0
0
0
0
1
1
0
0
$0C
REV7[v]
0
0
0
1
1
0
0
0
$18 bit i → bit 6 − i

It is built one bit at a time: LSR WORK pushes the low bit of v into C, ROL WORK+1 pushes C into the low bit of r — 7 times. Bits leave one number on the right and enter the other also on the right, so they line up in reverse order. Like moving a stack of plates onto another stack.

Two pages: a frame without flicker

The most important subroutine of the chapter is HERO_FRAME. If the hero were erased and redrawn on the visible page, the eye would catch the moment when he is absent — the figure would flicker. So everything is drawn on the hidden page, which is then shown with a single switch.

HERO_FRAME:
        LDA DPAGE               ; 1) the other page: $00 ↔ $20
        EOR #$20
        STA DPAGE
        ...
        JSR NPC_STEP            ; 2) one NPC moves
        LDX HPG                 ; 3) erase the hero where he is on THIS page
        LDA OLDX,X
        STA SX2
        LDA OLDY,X
        STA SY
        JSR ERASE_AT            ;    redraw the tiles from SCR_MAP
        JSR NPC_ERASE
        JSR NPC_REDRAW          ; 4) NPCs
        JSR HERO_DRAW           ; 5) the hero
        LDX HPG                 ;    remember where he is now on this page
        LDA HX2
        STA OLDX,X
        LDA HY
        STA OLDY,X
        LDA DPAGE               ; 6) show
        BEQ @one
        STA HISCR               ; $C055 — page 2 on screen
        RTS
@one:
        STA LOWSCR              ; $C054 — page 1
        RTS

EOR #$20 is a toggle. DPAGE is only ever $00 or $20. Flipping bit 5 gives $00 → $20 → $00 → … One instruction, no "if" needed.

Why the "old position" has two slots — OLDX/OLDY for each page. The page currently being drawn last showed the frame before the previous one. On it, the hero is not where he was in the previous frame but where he was two frames ago. That is where he must be erased. Here are four steps to the right:

FrameDrawn onHero erased atHero drawn atVisible
1page 2HX2 = 20 (OLDX[1])21page 2: 21
2page 120 (OLDX[0])22page 1: 22
3page 221 (OLDX[1])23page 2: 23
4page 122 (OLDX[0])24page 1: 24

Erasing means redrawing tiles. ERASE_AT does not "paint black". It determines which grid cells the hero's rectangle covered (2–3 columns × 1–2 rows) and redraws those tiles from SCR_MAP using SCR_TILEN from chapter 4. The cell number comes from the table MUL20: 0, 20, 40 … 180. Another multiplication replaced by a 10-byte table.

HERO_ENTER: a new screen is drawn in full on both pages (a third of a second each), and only then does the normal frame cycle begin.

HERO_MOVE: a step and "can he go there"

STEP_X:  .byte 0, 1, 0, 255        ; ↑ → ↓ ←: x / 2 ± 1 (255 = −1)
STEP_Y:  .byte 254, 0, 2, 0        ; lines: ± 2 (254 = −2)

        LDA HX2
        CLC
        ADC STEP_X,X
        CMP #133                 ; 0–132 (−1 = 255 is also ≥ 133)
        BCS @edge                ; off the edge of the screen

An elegant trick with the edge. At the left edge HX2 = 0, and a step of −1 gives 0 + 255 = 255. A single check, CMP #133 / BCS, catches both edges: "greater than 132" on the right and "less than 0" on the left — because −1 in a byte is 255, and 255 ≥ 133. Unsigned numbers wrapping around zero only help here.

HERO_FREE decides whether the hero can stand in the new spot. Not every pixel of the figure is checked, only the 4 corners of its lower half — the legs: x + 2 … x + 10, y + 8 … y + 15. The head may overlap a tree or roof cell — as in Zelda, the hero appears to stand in front of the tree. For each corner: its grid cell and that cell's flags:

CELL_WALK:
        CLC
        ADC MUL20,X             ; cell number = row × 20 + column
        TAX
        LDA SCR_MAP,X           ; tile number
        TAX
        LDA PASS_TAB,X          ; its flags
        AND WMASK               ; which ones to check
        EOR #P_WALK             ; 0 = exactly "walkable"
        RTS                     ; Z = 1 — allowed

CELL_WALK for rocks (6) and for dry grass (1)

bit
7
6
5
4
3
2
1
0
PASS_TAB[6]
0
0
0
0
0
0
0
0
$00 rocks: no flags at all
AND WMASK
0
0
0
0
0
0
0
1
$01
EOR #P_WALK
0
0
0
0
0
0
0
1
$01
=
0
0
0
0
0
0
0
1
$01 not 0 → Z = 0 → BNE @no: blocked
PASS_TAB[1]
0
0
0
0
0
0
0
1
$01 dry grass: P_WALK
AND WMASK
0
0
0
0
0
0
0
1
$01
EOR #P_WALK
0
0
0
0
0
0
0
1
$01
=
0
0
0
0
0
0
0
0
$00 0 → Z = 1: allowed

PASS_TAB holds a flag byte for each of the 112 tile numbers: P_WALK — walkable, P_SLOW — slow, P_LOOT — can be searched… AND keeps the relevant flags, EOR turns "exactly these" into zero. The answer is the Z flag, ready for BNE. For NPCs, WMASK also includes the P_ACT bit: doors are not passable for them, so they never enter houses.

Leg animation: every 3 steps HFR EOR #1 toggles the step number 0 ↔ 1. The same toggle as for the pages, only on bit 0.

Chapter 6. Transitions

The hero's position is a three-level address, like "city, street, house": the location HERE (0–255, a cell of the 16 × 16 region map), the screen GSCR (0–8, a cell of the 3 × 3 square inside the location) and the point on the screen HX2, HY. This chapter covers what happens when the hero reaches the edge of the screen.

A region is 48 × 48 screens

Ignoring locations, a region is simply a large grid of screens: 16 locations × 3 screens = 48 wide and as many high, 2,304 screens in total. A step to the right is always +1 to the "screen column". But that column is stored as two numbers: the location column (the low 4 bits of HERE) and the screen column inside it (GSCR mod 3):

screen column in region = (HERE AND $0F) × 3 + (GSCR mod 3)
screen row    in region = (HERE / 16)    × 3 + (GSCR / 3)

For the start location $37, screen 4: column 7 × 3 + 1 = 22, row 3 × 3 + 1 = 10. Moving "right" means adding 1 to 22 and seeing which location and which screen that lands on. Hence transitions have two cases: inside a location only GSCR changes; across its edge, both numbers change.

WALK_RIGHT and friends: four step subroutines

WALK_RIGHT:
        LDX GSCR
        LDA SCR_COL,X           ; screen column 0–2 (table 0,1,2,0,1,2,0,1,2)
        CMP #2
        BEQ @out                ; right column — leave the location
        INC GSCR                ; inside: just the next screen
        CLC
        RTS
@out:
        LDA HERE
        JSR WLD_RIGHT           ; right neighbour (chapter 1); C = 1 — region edge
        BCS @edge
        STA HERE
        DEC GSCR                ; 2 → 0, 5 → 3, 8 → 6
        DEC GSCR
        CLC
@edge:
        RTS
$37
012345678
→
$37
012345678
right, inside: screen 4 → 5 (INC GSCR)
$37
012345678
→
$38
012345678
right, across the edge: $37 screen 5 → $38 screen 3 (DEC × 2)
$37
012345678
↓
$27
012345678
up, across the edge: $37 screen 1 → $27 screen 7 (+6)

The rule for all four: across a location edge, the screen "moves" to the opposite side of the same row or column. Right: from column 2 to column 0, that is −2. Up: from row 0 to row 2, that is +6 (a row is 3 screens). Down: −6, left: +2.

The subroutines check the edge differently, each in the cheapest possible way:

DirectionEdge ifCheckInsideAcross the edge
→column 2SCR_COL,X / CMP #2 / BEQINC GSCRDEC DEC (−2)
←column 0SCR_COL,X / BEQDEC GSCRINC INC (+2)
↑GSCR < 3CMP #3 / BCCSBC #3ADC #6
↓GSCR ≥ 6CMP #6 / BCSADC #3SBC #6

For ← a BEQ right after LDA SCR_COL,X is enough, with no CMP: LDA itself sets Z if the column is 0. For ↑ and ↓ no table is needed at all: the row is visible in the number itself — 0–2, 3–5, 6–8. These are the "less than" and "greater than or equal" checks from the branch table in chapter 0. The answer "moved / region edge" comes back in the carry flag, just like WLD_RIGHT, on which WALK_RIGHT relies.

A small detail: DEC GSCR twice instead of "subtract 2". DEC works directly on memory and leaves A and the carry flag untouched, while subtraction would take LDA / SEC / SBC #2 / STA: 4 instructions and a clobbered A.

HERO_EDGE: check first, draw later

The hero has stepped past the edge of the screen. On the neighbouring screen, a tree or a house may stand at that edge; then the transition is not allowed and the hero simply stays. But finding that out requires the map of the other screen. The solution is a "trial fit": build the other screen, check it, and if the move is not allowed, restore everything.

  1. Remember the origin: OHERE, OSCR and the 32 bytes of the NPC table (OBJ_SAVE).
  2. Neighbour: WALK_UP / RIGHT / DOWN / LEFT according to the direction HDIR. At the region edge, control goes to REG_EDGE (chapter 14).
  3. Stand at the opposite edge: moving right gives x / 2 = 0 on the new screen, moving up gives y = 144. Table EDGE_V: 144, 0, 0, 132 for ↑ → ↓ ←.
  4. Build the other screen: if the location is different, LOC_LOAD, then SCR_GEN. This only computes SCR_MAP, with no drawing, and takes a fraction of a second.
  5. Can the hero stand there? HERO_FREE from chapter 5, on the new map.
  6. Yes: new NPCs, SCR_SHOW draws both pages, SUP_STEP deducts water and food for the transition (chapter 10, together with health). No: restore GSCR, HERE, rebuild the original map and NPCs, and stay put.

Why this order rather than "draw first"? Building a map is chapters 3 and 1: pure computation. Drawing is chapter 4: a third of a second per page. If the game drew first, every attempt to walk into a tree would flip the screen there and back for a second.

Details from HERO_EDGE

        LDX #31                 ; NPCs of the current screen — in case of "go back"
@sv:
        LDA OBJ,X
        STA OBJ_SAVE,X
        DEX
        BPL @sv                 ; X = 31 … 0, then $FF — stop

A count-down loop. Copying could go upward from 0, but then a CPX #32 is needed at the end. Counting down makes the check free: DEX itself sets the N flag, and while X is in 0–127, bit 7 is 0, so BPL ("branch if plus") branches. When X goes from 0 to $FF, bit 7 = 1 and the loop ends. The limitation: this works only if the starting X ≤ 127.

DEX and the N flag at the end of the loop

bit
7
6
5
4
3
2
1
0
X = 1
0
0
0
0
0
0
0
1
$01
DEX
0
0
0
0
0
0
0
0
$00 N = 0 (bit 7 = 0) → BPL branches: copy OBJ+0
DEX
1
1
1
1
1
1
1
1
$FF N = 1 → BPL does not branch: done
@went:
        BCC @inreg
        JMP REG_EDGE            ; region edge — into the neighbouring region
@inreg:

Why not simply BCS REG_EDGE? All conditional branches (BEQ, BCS…) are relative: the instruction holds not an address but an offset of −128…+127 bytes. REG_EDGE lives in another file, thousands of bytes away; a relative branch cannot reach it and the assembler reports an error. So the condition is inverted: "if C = 0, jump over the JMP", and a JMP with a full address reaches anywhere. This is a standard 6502 technique, the "long conditional branch".

        LDA HDIR
        BNE @n0                 ; 0 — up
        JSR WALK_UP
        JMP @went
@n0:
        CMP #1
        BNE @n1
        ...

Choosing one of four with a chain. In chapter 0 the arrow keys were looked up in a table. Here there are only 4 options and each is a call to a different subroutine, so a chain of comparisons is simpler. The first check, CMP #0, is omitted: LDA HDIR has already set Z.

HERO_SPAWN: where to place the hero in a new place

When the hero appears not through an edge but "out of the sky" — a new game, a trip by bicycle, loading a saved game — the hero must be placed on a walkable spot. The centre is tried first: x / 2 = 70, y = 56, which puts the feet in cell row 4, where every road runs. If that spot is taken, a search follows: rows every 8 pixels, columns every 7 (x / 2), top to bottom, until the first free cell. The same HERO_FREE answers "allowed?".

HUD: "LOC 37 SCREEN 4"

At the bottom of the screen (rows 22–23), SCR_INFO prints the name, type and "address" of the hero. Two small tricks:

Digit → character: ORA #$B0

bit
7
6
5
4
3
2
1
0
GSCR
0
0
0
0
0
1
0
0
4
ORA #$B0
1
0
1
1
0
0
0
0
$B0
= character
1
0
1
1
0
1
0
0
$B4 "4" on the Apple screen

The digit characters on the Apple are consecutive: "0" = $B0, "1" = $B1 … "9" = $B9 (ordinary ASCII $30–$39 plus bit 7, chapter 0). The low 4 bits of a digit code are the digit itself, and in the mask $B0 they are zero. So ORA simply "glues" the digit onto the right upper part — the same "switch on the free bits" technique as the "+ 32" for syllables in chapter 2.

Chapter 7. NPCs

Besides the hero, a screen can hold up to four figures: residents, guards, raiders, survivors and dogs. Each one decides for itself whether to stand or walk, whether it sees the hero, and what to do then. And all of them are drawn together with the hero on the same two pages, without flicker. The whole "life" of a screen is a single table of 32 bytes.

The OBJ table: 4 rows of 8 bytes

At address $0360 there are 4 "slots", 8 bytes each. A field number is the offset from the start of the slot, and each field has a name (OBJ_TYPE = 0, OBJ_X2 = 1 …). Here is the table right after entering screen 4 of the start location:

SlotAddress+0 type+1 x / 2+2 y+3 facing+4 step+5 state+6 timer+7 host.
0$0360$02
guard
$0E$2C$03$00$00$00$06
1$0368$01
resident
$4C$74$00$01$00$06$02
2$0370$00
—
$00$00$00$00$00$00$00
3$0378$00
—
$00$00$00$00$00$00$00

It reads as follows: slot 0 holds a guard (type 2) at x / 2 = 14, y = 44, facing left (3), walking (state 0), hostility 6. Slot 1 holds a resident, hostility 2. Slots 2 and 3 are empty: type 0 means "nobody".

To access a field of a given NPC, X is loaded with slot × 8 and the field name is added to the address: LDA OBJ+OBJ_Y,X with X = 8 reads $0360 + 2 + 8 = $036A, the resident's y. The assembler itself folds OBJ+OBJ_Y into a single number, $0362. This way the 32-byte table looks like an "array of records" in the code.

Visiting all four is a loop in which X grows by 8:

@next:
        TXA
        CLC
        ADC #8                  ; next slot
        TAX
        CPX #32                 ; 4 slots × 8
        BNE @o

Sometimes the slot number 0–3 is needed rather than × 8 (for small tables with one byte per NPC — "home", "already attacked"). Then three LSRs: 24 → 12 → 6 → 3.

OBJ_GEN: who appears on the screen

The population of a screen comes from the ROSTER table, 12 rows of 6 bytes: a base, a mask for the random extra, and up to 4 types in order. Rows 0–3 are settlements by kind (village, town, industrial zone, camp); rows 4–11 are the outskirts by "point of interest" from chapter 3 (filling station, cars, warehouse…).

ROSTER:     ; base, mask, type1, type2, type3, type4
        .byte 2, 1, 1, 2, 1, 1          ; village — 2–3, guard second
        .byte 3, 1, 2, 1, 1, 1          ; town — 3–4, guard first
        .byte 2, 1, 2, 1, 1, 0          ; industrial zone — 2–3   ← screen 4
        .byte 2, 1, 3, 3, 3, 0          ; camp — raiders 2–3
        ...
        .byte 0, 3, 5, 5, 0, 0          ; 7 empty — dogs 0–2

The number of NPCs: base + (random AND mask). Mask 1 gives +0 or +1, mask 3 gives 0 to 3. On screen 4 the result was 2 + 0 = 2: a guard and a resident, the first two types of the row.

Row number × 6 without multiplication: × 4 + × 2. The same technique as × 20 = × 16 + × 4 in chapter 3.

Where to place them. In a settlement, at one of the template's 8 "spawn points" (the SPAWN table: on the road, by the gate, by the tents), starting with a random one and going round. In the outskirts, at a random cell. A spot is acceptable if the feet are on walkable ground, no other NPC is there (HERO_FREE checks that too) and it is no closer than 12 / 24 pixels to the hero, so nobody appears right next to the hero. If 16 attempts find no spot, that NPC is skipped. The spawn spot is remembered as "home" (HOMEX, HOMEY): the NPC never wanders farther than its type's radius.

Cell → point: x / 2 = column × 7 (ASL ASL ASL = × 8, then SBC column = × 7), y = row × 16 − 8 (so that the feet, the lower half of the figure, stand in that cell).

NPC_HOST: hostility

The key number of an NPC is its hostility towards the hero, field +7. It is computed once, at spawn time:

hostility = type base + (7 − location order) / 2 + 4 − reputation with its group / 2   (at least 0)
TypeBase(7 − 6) / 2+4Group, reputation− rep. / 2TotalBehaviour
resident204residents, 8−42friendly
guard404guards, 8−44 +2 = 6wary (+2: hero's status below NEIGHBOUR)
raider904raiders, 4−211hostile
dog1504none—19hostile

These are exactly the numbers in the table above: guard 6, resident 2. The order of $37 is high (6), so the "disorder" term is almost zero. In an anarchic location (order 0), everyone gets another 3. The better the reputation with a group, the calmer its people: this is the rule "where order is kept, people are calmer".

7 − order in one instruction: EOR #%00000111

bit
7
6
5
4
3
2
1
0
order
0
0
0
0
0
1
1
0
6
EOR #%111
0
0
0
0
0
1
1
1
7
= 7 − 6
0
0
0
0
0
0
0
1
1

For numbers 0–7, "7 − x" simply flips the three low bits: 7 = 111, and subtracting from all ones means turning 1 into 0 and vice versa, with no borrows. One instruction instead of LDA #7 / SEC / SBC, and no second register needed. Raiders have one more detail: even a "friendly" one (hostility below 8) gets 8 in 1 case out of 8 anyway, and attacks.

NPC_STEP: one NPC moves per frame

Thinking for all four on every frame is expensive. So one NPC moves per frame, in turn:

        LDA NTURN               ; whose turn: 0 → 8 → 16 → 24 → 0
        CLC
        ADC #8
        AND #%00011000          ; 32 → 0: only bits 3–4 remain
        STA NTURN

Wrap-around counter: 24 + 8 = 32 → 0

bit
7
6
5
4
3
2
1
0
NTURN
0
0
0
1
1
0
0
0
24
ADC #8
0
0
1
0
0
0
0
0
32
AND #%00011000
0
0
0
1
1
0
0
0
=
0
0
0
0
0
0
0
0
0 slot 0 again

The mask keeps only bits 3 and 4, which are exactly the numbers 0, 8, 16, 24. Bit 5 (32) is cut off and the counter wraps around by itself. "Remainder of division by 32" in a single instruction works whenever the divisor is a power of two.

An NPC's decision depends on hostility, in three tiers:

HostilityIf it sees the heroIf it does not
0–3 · friendlystands facing the hero, waitswanders
4–7 · warycloser than 2 cells — runs awaywanders
8+ · hostilepursues; when adjacent — attacks (chapter 10)wanders

The checks run in sequence, CMP #8 / BCS @host, CMP #4 / BCS @wary: first "≥ 8", then "≥ 4", otherwise less than 4. The order matters: 11 is also ≥ 4, but it never reaches that check.

Running away is pursuit in reverse: the direction towards the hero is flipped with EOR #2. Directions are numbered ↑0 →1 ↓2 ←3 clockwise, and the opposite one always differs by 2: 0 ↔ 2, 1 ↔ 3. Flipping bit 1 is exactly "± 2".

NPC_SENSE: where the hero is, and the absolute value

An NPC needs the distance to the hero along x and y and the direction to move towards the hero. A distance is the absolute value of a difference, and the 6502 knows nothing about negative numbers. The subroutine ABSC takes three instructions:

        LDA OBJ+OBJ_X2,X         ; guard's x / 2 = 14
        SEC
        SBC HX2                   ; − hero 70
        BCS @r                    ; C = 1: result ≥ 0 — already the absolute value
        EOR #$FF                  ; C = 0: went negative —
        ADC #1                    ;   flip the sign: (A XOR $FF) + 1

|14 − 70| = 56

bit
7
6
5
4
3
2
1
0
14 − 70
1
1
0
0
1
0
0
0
$C8 = −56 in a byte (256 − 56 = 200); C = 0 — there was a borrow
EOR #$FF
0
0
1
1
0
1
1
1
$37 all bits inverted = 55
ADC #1
0
0
1
1
1
0
0
0
$38 +1 (C = 0, nothing extra is added) = 56

This is "two's complement": −x in a byte is written as 256 − x and is turned back by inverting the bits and adding 1. The trick is that no CLC is needed before ADC #1: control arrives here precisely because C = 0 after the failed subtraction. The game computes absolute distances dozens of times — for NPCs, for "not closer to the hero", for combat.

Next: whichever axis has the larger distance is the first direction to move (NDIR1), and the other axis is the fallback (NDIR2) if the first step hits a wall. A detail: x is stored halved, so before comparing it with y it is doubled with ASL A, and if a carry comes out (more than 255 pixels), the x distance is certainly larger.

Line of sight (IN_SIGHT) is simply "distance less than the type's range" on both axes: tables TSX, TSY. A guard sees 4 cells, a raider 5, a dog 6.

Wandering: stand or walk, but not far from home

When an NPC's timer (field +6) reaches zero, NPC_CHOOSE decides what comes next: in 1 case out of 4, stand still; otherwise, walk in a random direction. How long is also random, using the type's masks from the TPAR table: a resident wanders nearby and often stands, a raider walks far, a dog runs 2 steps per turn. If an NPC has gone farther from home than its type's radius, the next direction is not random but towards home. That is why a guard "keeps to the post" while a raider roams the whole screen.

A step is NPC_MOVE1: the same STEP_X / STEP_Y as for the hero, the same edge check CMP #133, and the same HERO_FREE. Two differences are passed in variables: NSELF — "do not count yourself as an obstacle" (for the hero it holds $FF — check everyone) and WMASK with the P_ACT bit — NPCs do not enter doors, gates or shops. One check subroutine serves everyone.

Draw only what has changed

The hero is redrawn every frame. NPCs are not: if one stands still, there is no reason to touch it. For this, each page keeps its own record of "where and how it is drawn here", DRW: 4 bytes per slot (x, y, facing, step), 16 per page. Like OLDX for the hero in chapter 5, only for four figures.

  1. NPC_ERASE: for each NPC, compare the 4 table fields with this page's DRW record. If everything matches, do nothing. If something has changed, erase it where it is drawn on this page (ERASE_AT, redrawing the tiles) and mark it "redraw" with a bit in NDIRTY (slot 0 → 1, slot 1 → 2, slot 2 → 4, slot 3 → 8 — the DIRTY_BIT table; four NPCs, four bits of one byte).
  2. Every erased rectangle of cells goes into a list (ER_ADD, up to 5 entries). The erased hero goes there too.
  3. NPC_REDRAW: draw the marked ones, and also those touched by erasing. Nobody touched a standing resident, but if the hero walked past, redrawing the tiles under the hero also erased half of the resident. ER_HIT checks whether an NPC's rectangle intersects any erased one.

The intersection of two rectangles takes four comparisons: "my left edge ≤ its right edge, my right edge ≥ its left edge", and the same for rows. If all four hold, they intersect. In code this is a chain of CMP / BEQ / BCS: "≤" on the 6502 means "equal or less", that is BEQ (equal) or not BCS (less).

Chapter 8. HUD and texts

Below the picture there are four lines of text: where the hero is, what kind of place it is, health, and messages ("THE RAIDER ATTACKS!"). These are not drawn letters but the real Apple II text screen, "glued" to the bottom of the graphics. This chapter covers how text is stored in memory, why it has to be copied to the second page, how a HUD line is assembled from pieces, and where the game's 110 phrases live.

Mixed mode: 160 lines of graphics + 4 lines of text

The MIXSET switch ($C053) in SCR_ON (chapter 0) turns on a mode in which the top 160 pixel lines are HiRes and the bottom 32 are rows 20–23 of the ordinary text screen. The text screen is 40 × 24 characters, 1 KB of memory: page 1 is $0400–$07FF, page 2 is $0800–$0BFF. One byte is one character.

Text rows are laid out in the same "staircase" as HiRes lines (chapter 4) — it is the same video counter scheme, only without the "lines within a band": address = $0400 + (row mod 8) × $80 + (row / 8) × $28.

RowPage 1Page 2Contents
20$0650$0A50whose screen: "SETTLEMENT 1 TOWN LV 6" / "OUTSKIRTS FARM"
21$06D0$0AD0messages
22$0750$0B50location name and type
23$07D0$0BD0"LOC 37 SCREEN 4" and health, water, food

Row 20: 20 mod 8 = 4 → 4 × $80 = $200; 20 / 8 = 2 → 2 × $28 = $50; $0400 + $200 + $50 = $0650. Page 2 is the same plus $400.

HUD_COPY: why the text lives in two places

A subtlety of mixed mode: the page number is shared. When HiRes page 2 is shown (HISCR), the text at the bottom is also taken from page 2, at $0800. And frames are drawn alternately on both graphics pages (chapter 5). So the HUD must be identical on both text pages; otherwise it would vanish every other frame.

The game always prints to page 1 — that is how COUT in ROM works. Then HUD_COPY copies the four rows to page 2:

HUD_COPY:
        LDX #39                 ; 40 characters, X = 39 … 0
@c:
        LDA $0650,X             ; row 20
        STA $0A50,X
        LDA $06D0,X             ; row 21
        STA $0AD0,X
        LDA $0750,X             ; row 22
        STA $0B50,X
        LDA $07D0,X             ; row 23
        STA $0BD0,X
        DEX
        BPL @c                  ; count down to 0 — chapter 6
        RTS

Four rows per loop pass rather than four loops of 40: the counter and the branch are paid for 40 times instead of 160. This is an "unrolled" loop, a common technique when speed matters more than a couple of bytes of code.

A side benefit: only 4 rows of text page 2 are visible on screen. The other 20 rows — almost 900 bytes — are "invisible" memory, and the game keeps tables there: the screen map SCR_MAP ($0800, chapter 3), settlement growth, the backpack. Space that would otherwise go to waste.

The cursor and COUT

COUT ($FDED) prints the character in A at the cursor position and moves the cursor right. The cursor is two cells of the ROM monitor: CH ($24) is the column, CV ($25) is the row. Putting the cursor at the start of row 20:

        LDA #20
        STA CV                  ; row
        JSR VTAB                ; ROM recomputes the row address into BASL — $0650
        LDA #0
        STA CH                  ; column

VTAB handles the "staircase" itself: from the row number it computes the row address and puts it in BASL ($28/$29). After that, COUT writes to address BASL + CH. CLREOL clears the row from the cursor to the end, so an old long text does not leave a tail behind a new short one.

HUD_ROLE: a line made of pieces

Row 20 — "SETTLEMENT 1 TOWN LV 6" — is not stored anywhere as a whole. It is assembled from five pieces:

SETTLEMENT TXT_SETTL1LOC_ROLE → ORA #$B0 $A0TOWNTXT_KINDS[kind] LV TXT_LV6SET_LVL → ORA #$B0

Fixed words are zero-terminated strings (HUD_PUTS, chapter 2). Numbers use ORA #$B0, digit → character (chapter 6). A word by number comes from an address table: kind 0–3 × 2 → TXT_KINDS → VILLAGE / TOWN / WORKS / CAMP. The same technique as for name syllables. For the outskirts, "OUTSKIRTS" and the point-of-interest word from TXT_POIS are used instead: GAS STATION, CAR WRECKS, FARM…

This way two or three dozen short words produce every variant of the line, taking less space than one full line of each kind would.

110 phrases: messages by number

All of the game's phrases — "BAG IS FULL", "THE SETTLEMENT GROWS!", "NOT ENOUGH CASH", the market and status window headings, region names — are stored not where they are printed but in one place, and each has a number. The code says "print phrase 10", not "print these letters". This is arranged with two files.

lcmsg.s holds the phrases themselves and the table of their addresses. It is part of DATA, that is, the hidden memory:

TXT_MSG:        .word MS_P0, MS_EQ0, MS_EQ1, MS_EQ2, MS_EQ3, MS_EQ4, MS_FOUND, MS_NOTH   ; 0–7
                .word MS_DONE, MS_FULL, MS_GREW, MS_CASH, …                         ; 8, 9, 10 …
                ...
MS_P0:          .byte 0                                   ; phrase 0 — empty
MS_EQ0:         .asc "KNIFE"
                .byte 0
                ...
MS_GREW:        .asc "THE SETTLEMENT GROWS!"
                .byte 0

This is the same scheme as the syllables in chapter 2: zero-terminated strings and an address table in which the position in the table is the phrase number. MS_GREW is eleventh in TXT_MSG, so its number is 10 (counting from zero).

msgnum.s holds names for the numbers. It is part of MAIN:

M_P0            = 0   ; ""
M_EQ0           = 1   ; "KNIFE"
...
M_GREW          = 10  ; "THE SETTLEMENT GROWS!"
...
M_SAVED         = 109 ; "GAME SAVED"

A line of the form NAME = number is not data but a hint to the assembler: "wherever M_GREW appears, substitute 10". Not a single byte of it remains in the built MAIN. The whole of vars.s (chapter 0) works the same way: KBD = $C000, SEED = $10 — names instead of bare numbers.

One rule is essential: the number in msgnum.s and the position of the address in the TXT_MSG table must match. Inserting a new phrase in the middle of the table shifts all numbers after it, and they must be corrected in both files.

Why numbers at all? Space for code is the scarcest resource in the game: between the second graphics page and DOS there are only 14,720 bytes (chapter 0). The phrases sit in hidden memory, and MAIN keeps only their numbers — one byte each in an LDA #M_… instruction. This way texts do not take space needed by code.

In code, a message takes two instructions:

        LDA #M_GREW              ; A = 10
        JMP MSG_N               ; print in row 21 (tail call)
MSG_N:                          ; message number A in row 21 (both pages)
        PHA                     ; number onto the stack: MSG_CLEAR clobbers A
        JSR MSG_CLEAR           ; cursor to row 21, clear it
        PLA                     ; number back
        JSR PUT_MSG
        JMP HUD_COPY            ; and to the second page

PUT_MSG:
        ASL A                   ; number × 2
        TAX
        BIT LCRAM               ; the table is in hidden memory
        LDA TXT_MSG,X
        STA STR
        LDA TXT_MSG+1,X
        STA STR+1
        BIT LCROM
        JMP HUD_PUTS            ; HUD_PUTS fetches the characters from the card itself
StepNumbersWhat happens (M_GREW = 10)
PHA … PLAA = 10PHA pushes A onto the stack, PLA pulls it back. The stack is the fastest "pocket": one instruction in, one out, no address.
ASL A20 ($14)Addresses are 2 bytes each.
LDA TXT_MSG,X$EC12 + $14 = $EC26 → $48Low byte of the phrase address.
LDA TXT_MSG+1,X$EC27 → $EDHigh byte. STR = $ED48.
HUD_PUTS$ED48: $D4 $C8 $C5 $A0 …"T", "H", "E", space… up to the 0 byte.

The same mechanism as the name syllables (chapter 2), with the same limitation: number × 2 must fit in a byte, so there can be at most 128 phrases. There are 110 now, leaving 18 spare.

A useful property of this layout: lcmsg.s is included last in DATA, and the TXT_MSG table comes first in it. So changing the text of a phrase without changing the number of phrases does not move the table address — only DATA needs rebuilding, and MAIN stays as it is.

What a character looks like on the text screen

bit
7
6
5
4
3
2
1
0
"A" normal
1
1
0
0
0
0
0
1
$C1
"A" inverse
0
0
0
0
0
0
0
1
$01
"A" flashing
0
1
0
0
0
0
0
1
$41

The two high bits of an on-screen code are the mode: 11 / 10 — a normal character, 00 — inverse (dark letter on light), 01 — flashing. Hence the "bit 7" in all the game's strings (chapter 0). Inverse comes in handy in chapter 13: the cursor on the map is a cell whose two top bits are simply cleared: AND #%00111111.

Chapter 9. Market and search

The space bar does one of two things. On a settlement screen it opens the market: buy, sell, equipment. On any other screen it searches: something may turn up in the ruins. Neither the market nor the finds are stored: prices, stock, "what is made here and what is needed" — all of it is recomputed from the seed on every visit. Only what the player has changed is stored: money, the backpack, "already searched" and "how much the settlement has grown".

ACT_KEY: one key, five cases

ACT_KEY:
        LDA #2
        STA CWANT
        JSR CMB_NEAR            ; stunned NPC nearby? — search it (chapter 10)
        BCC @sub
        JMP CMB_LOOT
@sub:
        JSR SUB_HERE            ; substation yard? — its window (chapter 12)
        BCC @trade
        JMP SUB_SHOW
@trade:
        LDA HERE
        JSR WLD_GET             ; location seed → SEED (chapter 1)
        LDX GSCR
        LDA LOC_ROLE,X
        BEQ @search             ; 0 — outskirts: search
        JMP MKT_OPEN            ; 1–3 — settlement: market
@search:
        JMP SRCH_DO

The order of the checks is the priority: the most specific case first (an NPC lying nearby), then the place (a substation), then the general rule (settlement or not). Every answer comes back in the C flag, every branch is a tail call JMP: ACT_KEY does nothing itself, it only chooses who gets the work.

Market: what is made and what is needed

QUINTAMATERA market: 16 goods, prices, stock, backpack; at the bottom NEEDS CLOTHES, MAKES CANDLES
Market of the town QUINTAMATERA (screen 3, level 6). At the bottom: NEEDS CLOTHES — MAKES CANDLES.

The market takes the whole screen as text, like a station in Elite: TXTSET switches graphics off, the HiRes pages are left untouched, and on exit the picture comes back exactly as it was. Every settlement has two "specialities": which good it makes (cheap, plenty) and which it needs (expensive, not for sale). Both come from the high halves of seed bytes, 4 bits each, that is a good number 0–15:

MKT_CALC: "makes" and "needs" for $37

bit
7
6
5
4
3
2
1
0
SEED+3
0
1
1
1
1
1
1
0
$7E
4 × LSR
0
0
0
0
0
1
1
1
7 makes: good 7 — CANDLES
SEED+5
1
0
0
1
0
0
1
1
$93
4 × LSR
0
0
0
0
1
0
0
1
9 needs: good 9 — CLOTHES

The same bytes already served the name (chapter 2, low 5 bits) — here the high 4 are taken. If "makes" and "needs" coincide, "needs" moves on to the next good: ADC #1 / AND #%00001111 — wrapping around 0–15. Developed locations (type 3) do not take stolen goods: if they "need stolen goods", that is replaced with medicine.

Prices and stock — as in Elite

Each of the 16 goods has three numbers in tables: base price, variation mask and rarity.

;                  WAT CAN FRS FUE BUT MED BAT CND SED CLO TOL PRT SOL WIN ROP STL
PBASE:          .byte 2, 4, 3, 12, 10, 20, 6, 2, 5, 6, 15, 18, 60, 8, 3, 25
PVAR:           .byte 1, 3, 3, 7, 3, 7, 3, 1, 3, 3, 7, 7, 15, 3, 1, 7
PRARE:          .byte 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 2, 0, 0, 2
price = base + (random AND mask)
        made here    — halved  (LSR A)
        needed here  — doubled (ASL A)
stock = needed here → 0
        made here   → 8 + level × 2
        rarity 2    → 0   (solar panels, stolen goods — only found)
        rarity 1    → 1–4 at half of the markets, 0 at the rest
        ordinary    → 2–9 + level
GoodBase + variationSpecialPriceStockOn screen
7 CANDLES2 + 0…1made: ½18 + 6 × 2 = 201 · 20
9 CLOTHES6 + 0…3needed: × 212012 · 0
12 SOLAR PANELS60 + 0…15rarity 270070 · 0
0 WATER2 + 0…1ordinary32…9 + 63 · 10

The masks in PVAR are 1, 3, 7, 15: numbers made of "all ones". AND with such a mask gives a uniform random number 0…mask — with no division and no "remainder". That is why expensive goods have a wider price spread: ±15 for panels, ±1 for water.

A small detail in @rnd: the generator is started from the screen seed (chapter 3), but then EOR #%00111100 is applied. Otherwise the first "random" numbers of the market would match the first numbers of that screen's map, and prices would be tied to where the rocks lie. The search does the same with its own mask %10100111.

Money is 16 bits: "is there enough?"

Money can exceed 255 euros, so CASH is two bytes. A price is one byte. "Is there enough money" is a 16-bit comparison done in four instructions:

        LDA CASH                ; low byte of money
        CMP MPRICE,X           ; − price: C = 0 if there was a borrow
        LDA CASH+1              ; high byte of money
        SBC #0                  ; − 0 − borrow
        BCC @poor               ; C = 0 — not enough

CMP subtracts the low bytes and leaves "was there a borrow" in the carry flag (chapter 0). SBC #0 subtracts 0 from the high byte — plus that borrow. If the borrow pushed the high byte below zero, C = 0: there is less money than the price. The result itself is not needed — only the flag.

256 € and price 12: enough

bit
7
6
5
4
3
2
1
0
CASH lo
0
0
0
0
0
0
0
0
$00
CMP price
0
0
0
0
1
1
0
0
$0C $00 − $0C: borrow → C = 0
CASH+1
0
0
0
0
0
0
0
1
$01
SBC #0 and borrow
0
0
0
0
0
0
0
1
$01 − 0 − 1
=
0
0
0
0
0
0
0
0
$00 C = 1 — borrow absorbed: enough money

256 − 12 = 244, there is enough money, even though the low byte ($00) is smaller than the price. This is why looking only at the low byte is not enough.

10 € and price 12: not enough

bit
7
6
5
4
3
2
1
0
CASH lo
0
0
0
0
1
0
1
0
$0A
CMP price
0
0
0
0
1
1
0
0
$0C borrow → C = 0
CASH+1
0
0
0
0
0
0
0
0
$00
SBC #0 and borrow
0
0
0
0
0
0
0
1
=
1
1
1
1
1
1
1
1
$FF went negative → C = 0 → BCC @poor

Deducting money is the same pair with a real subtraction (SEC / SBC on the low bytes, SBC #0 on the high). Adding money on a sale is CLC / ADC and ADC #0, as in chapter 1. And if the sum goes past 65 535 (a carry out of the high byte), money is simply set to $FFFF — it cannot go higher.

PRNUM: how to print "350"

The processor cannot divide by 10, yet decimal digits must be printed. The solution is to subtract powers of ten while possible and count how many times it worked:

P10_LO:  .byte $10, $E8, 100, 10, 1      ; 10000 = $2710, 1000 = $03E8
P10_HI:  .byte $27, $03, 0, 0, 0
Digit placeSubtractTimes it workedRemainder
10 000$27100 — 350 is smaller350
1 000$03E80350
100$00643: 350 → 250 → 150 → 5050
10$000A50
1$000100

Digits 0, 0, 3, 5, 0. Leading zeros are replaced with spaces (when the number must be right-aligned in a column) or skipped; the last digit is always printed. Each digit becomes a character with ORA #$B0 (chapter 6). The subtraction is a trial: the result goes into NUM only if it did not go negative (BCC @next — next digit place). This is how prices, stock, money and status points are printed.

Selling what is needed — settlement growth

The main market mechanic: sell a settlement what it needs, 2 × (level + 1) units in one visit, and its level goes up by 1 (up to 7). A level-6 town needs 14 units of clothes. Every unit of the needed good also gives the hero +1 status; growth gives +8 status and +1 reputation with the residents.

        LDA SET_LVL,Y           ; level 6
        CMP #7
        BCS @done               ; already 7 — no room to grow
        CLC
        ADC #1                  ; 7
        ASL A                   ; 14
        CMP MSOLD               ; 14 sold already?
        BNE @done
        JSR GROW_INC            ; record the growth

Where to store growth when there are 3 settlements in each of 256 locations? Growth is at most 7, which is 3 bits. So one LOC_GROW byte holds two settlements: the first in the low 4 bits, the second in the high 4. The third goes into the low 4 bits of a second table, LOC_GROW3. 512 bytes for the whole region instead of 768.

LOC_GROW: two settlements in one byte

bit
7
6
5
4
3
2
1
0
LOC_GROW,X
0
0
1
0
0
0
0
1
$21 high 4: settl. 2 grew by 2 · low 4: settl. 1 by 1
settl. 1: AND #$0F
0
0
0
0
0
0
0
1
1
settl. 2: 4 × LSR
0
0
0
0
0
0
1
0
2
settl. 2 grows: + 16
0
0
1
1
0
0
0
1
$31 ADC #16 = +1 to the high half

Half a byte is called a "nibble". Adding 1 to the low nibble is just INC. To the high one — ADC #16: 16 is a one in bit 4. Overflow cannot happen: growth is triggered only while the level is below 7.

GROW_GET:                       ; Y = settlement 0–2
        LDX HERE
        CPY #1
        BEQ @s1                 ; Y = 1
        BCS @s2                 ; Y > 1, i.e. 2
        ...                     ; Y = 0

A choice among three with a single comparison: CPY #1 sets both Z and C. Z = 1 — equal to 1; otherwise C = 1 — greater; otherwise — less. Two branches in a row on the same flags.

On entering a location, LOC_GROWN adds the growth to the level from the seed (no more than 7) — and the settlement template (chapter 3) rebuilds ruins into houses by itself. On leaving a market where the settlement grew, the game rebuilds the screen (SCR_GEN), so the growth is visible at once.

Search: one find per screen, once

On an outskirts screen the space bar searches. Whether something is found, and what, comes from the screen seed: a find on 1 screen in 4; what exactly — from the LOOT table by point of interest (petrol and butane at a filling station, medicine at a pharmacy, occasionally a substation part at a power line); how many — 1–3. Searching costs time: water and food are used up as for a screen transition.

Each screen can be searched only once. "Searched" is one bit per screen. A location has 9 screens, but settlements cannot be searched — at most 6 outskirts screens remain, and bits 0–5 of one LOC_SRCH byte are enough for them. Bit 6 of the same byte is "been here", for the map fog (chapter 13).

Which bit belongs to a screen? Not by screen number, but by its position among the outskirts screens. In $37 the settlements are on screens 1, 3, 4; the outskirts are 0, 2, 5, 6, 7, 8:

Screen012345678
Roleoutsk.settl. 2outsk.settl. 1settl. 3outsk.outsk.outsk.outsk.
Bit0 ($01)—1 ($02)——2 ($04)3 ($08)4 ($10)5 ($20)

SRCH_BIT walks the screens from 0 up to the current one and shifts the bit left (ASL MBIT) on every outskirts screen. When it arrives, the bit is ready. The check "already searched?" is AND LOC_SRCH,X, marking is ORA (the same "set a bit" as for road seams in chapter 3).

A small detail: if the backpack is full, the bit is not set — the player can come back with an empty backpack and still collect the find. And if less fits than was found, as much as fits is taken.

Backpack: 16 bytes

BAG is 16 consecutive bytes, one per good: how many units the hero carries. The total is BAG_SUM, a loop adding 16 bytes counting down. How much fits is BAG_CAP: 20, big backpack +10, motorbike +10, otherwise bicycle +5. Equipment is the bits of one byte, EQUIP: knife, backpack, pistol, bicycle, motorbike. "Is there a bicycle" is LDA EQUIP / AND #EQ_BIKE / BEQ. Eight "have / have not" items in one byte.

Chapter 10. Combat and health

Combat in BLACKOUT works as in Elite: no finger dexterity, only an action and a dice roll. Press A next to an NPC and the game rolls a die against that type's chance. A hit — the NPC is down. Its pockets can then be searched, and it can be tied up if there is rope. It can also be killed — with a weapon — but that is paid for in reputation. This chapter also covers health, water and food.

A 16-sided die

Every roll in the game takes three instructions:

        JSR GEN_RND             ; random 1–255 (chapter 3)
        AND #%00001111          ; 0–15: a 16-sided die
        CMP CTMP                ; chance
        BCC @stun               ; rolled below the chance — success

The chance is a number 0–16: how many of the 16 faces "win". BCC is "A is less" from the branch table in chapter 0. The chances sit in tables by NPC type:

TSTUN:  .byte 0, 12, 8, 8, 8, 8      ; stun by hand: resident 12/16, others 8/16
TBITE:  .byte 0, 2, 4, 4, 2, 8       ; hit the hero: resident 2/16 … dog 8/16
0123456789101112131415
punching a resident: faces 0–11 win — 12 of 16 = 3/4
0123456789101112131415
a guard or a raider: 0–7 — 8 of 16 = 1/2
0123456789101112131415
weapon, knife: 6 of 16 = 3/8 (kill)
0123456789101112131415
weapon, pistol: 12 of 16 = 3/4

Why 16 and not 100, as in tabletop games? Because 16 is a power of two: AND #15 yields exactly 0–15, every outcome equally often. A 10-sided die would need division — and the processor has no division.

NPC states

Field +5 of the NPC table (chapter 7) is the state. Combat adds three new ones:

0 walking · 1 standingnormal life
A, success →
2 stunnedlies for 60 turns (~5 s), then gets up — angry
space + rope →
3 tied uplies while the hero is on the screen
0 · 1 · 2on its feet or lying
W, success →
4 killed2 turns — erase from both pages, then the slot is free

A drawing trick: for a lying NPC, the "step" field (+4) gets the same number as the state — 2, 3 or 4. For a walking one it holds 0 or 1. So the "step" field has changed, and NPC_ERASE from chapter 7 works out by itself that the NPC must be erased and redrawn — now lying down. No separate "redraw" is needed.

A killed NPC does not vanish at once for the same reason: it is drawn on both pages. State 4 means "do not draw", and over two turns it is erased first from one page, then from the other. Only then is the slot freed.

CMB_NEAR: who is right next to the hero

Both a punch and a search start with the question "who is nearby": closer than 10 in x / 2 and 20 in y. But a punch looks for someone on their feet, and a search for someone stunned. The variable CWANT decides: 0 — on their feet, 2 — stunned. The elegant part is how one check serves both cases:

        LDA OBJ+OBJ_ST,X
        CMP #2
        BCS @down               ; state ≥ 2 — lying
        LDA CWANT               ; on its feet — is that what is wanted?
        BNE @next
        BEQ @dist               ; yes — measure the distance
@down:
        BNE @next               ; ≥ 2 and not 2 — tied up or killed: not ours
        LDA CWANT               ; exactly 2 — stunned: is stunned wanted?
        BEQ @next

CMP #2 sets two flags at once, and they are enough for three answers: C = 0 — less than 2 (on its feet), C = 1 and Z = 1 — exactly 2 (stunned), C = 1 and Z = 0 — greater (tied up, killed). At the @down label the flags are still from the same CMP — BCS does not change them. The same trick as CPY #1 in chapter 9.

BNE @next / BEQ @dist in a row is "always jump": one of the two conditions is certainly true. This is written instead of JMP when the target is close: one byte shorter.

Pocket: a coin in the carry flag

Each NPC type carries one of two goods in its pocket: a resident — canned food or fresh food, a guard — medicine or batteries, a raider — petrol or stolen goods. A choice of two:

        JSR GEN_RND             ; which of the two
        LSR A                   ; bit 0 → carry flag: the coin
        LDA POCKA,Y             ; first option (LDA leaves the carry flag alone!)
        BCC @g
        LDA POCKB,Y             ; coin = 1 — the second
@g:

LSR as a coin toss

bit
7
6
5
4
3
2
1
0
RND
1
0
0
1
1
1
0
1
$9D
LSR A
0
1
0
0
1
1
1
0
$4E bit 0 (1) dropped into C → C = 1
LDA POCKA,Y
0
0
0
0
0
0
1
1
A = 3 (petrol), but C is still 1
BCC does not jump
0
0
0
0
1
1
1
1
LDA POCKB,Y: A = 15 — stolen goods

First the random bit goes into C, then the first option is loaded into A without worry — LDA changes only N and Z, the carry stays. Only then is the coin examined. Without this, the random number would have to be kept somewhere while the option is loaded.

A raider has one more roll — AND #%00000111 / BNE: a 1 in 8 chance that instead of a good it carries a weapon. First a knife, if the hero has none, then a pistol. A weapon is a bit in the EQUIP byte (chapter 9); "handing it over" is ORA #EQ_KNIFE.

Once the pocket is taken, the hostility field gets 14 (H_EMPTY): both "pocket empty" and "angry" (≥ 8 — hostile, chapter 7). One number, two meanings.

Tie up — and there will be fewer raiders

Space next to a stunned NPC: the pocket, and if the backpack holds rope (good 14), tying up as well. A tied raider pays off in the future: every location has a counter "how many raiders were tied up here" — the high 4 bits of the LOC_GROW3 byte, the free half of the same byte that holds the growth of the third settlement (chapter 9).

        LDA LOC_GROW3,X         ; high 4 bits — the counter, up to 15
        CMP #$F0
        BCS @say                ; already 15 — nowhere to go
        CLC
        ADC #16                 ; +1 to the high half
        STA LOC_GROW3,X

When NPCs appear on a screen of this location, each raider is rolled against the counter: GEN_RND / AND #15 / CMP counter / BCC — do not place. Four raiders tied up — each new one appears with a chance of 12 in 16. Fifteen tied up — almost nobody. There it is, the mechanic "bring order and the place gets calmer", in six instructions.

Killing: the price

W is a weapon strike with the best weapon available: pistol (12/16), otherwise knife (6/16). On success the NPC is killed and its pocket goes into the backpack. The price follows at once: reputation with the victim's group −4, with raiders another −2 ("avenger"), status −16, kill counter +1.

        LDA REPS,Y              ; reputation with the group
        SEC
        SBC #4
        BCS @r                  ; not negative — keep it
        LDA #0                  ; negative — zero, it cannot go lower
@r:
        STA REPS,Y

"Subtract, but not below zero" uses the carry flag after SBC: C = 0 means "there was a borrow, it went negative". The kill counter is the opposite, "add, but not above 255": CMP #255 / BEQ / INC. Without this check the 256th kill would turn the counter into 0, and the killer would look innocent to everyone. Such "stops" are needed wherever a byte can overflow.

The NPC strikes back

A hostile NPC right next to the hero (chapter 7) calls CMB_BITE. It does not strike every turn, but once every 12 of its turns (~1 s): the "timer" field counts the pause. A hit (a roll against TBITE) costs 1 health. When health reaches zero the hero does not die: all cargo is taken, the backpack is emptied, everyone on the screen calms down (hostility 0), health is back to 9. The penalty is lost goods, not the end of the game.

Health: rest and medicine

Health 0–9 is restored in two ways. M — medicine from the backpack: +5, but no more than 9 (CMP #HPMAX+1 / BCC — "≤ 9 keep, otherwise 9"). And rest — CMB_TICK, which the main loop calls every frame (chapter 0): if there is no hostile NPC on its feet on the screen and the backpack holds water and food, +1 every 10 seconds.

How to count 10 seconds without a clock? A frame counter. The game runs at roughly 45 frames per second, so there are two counters, one inside the other:

        INC RTICK               ; frames
        LDA RTICK
        CMP #FPS                ; 45 frames = 1 second
        BCC @r
        LDA #0
        STA RTICK
        INC RSEC                ; seconds
        LDA RSEC
        CMP #REGEN              ; 10 seconds
        BCC @r
        LDA #0
        STA RSEC
        INC HP                  ; +1 health

Like the minute and hour hands: one counts to 45 and resets, and the other steps by 1. Anything that forbids rest resets both, and rest starts over.

Water and food — like fuel in Elite

Supplies are used up not by the clock but per transition between screens (and per search): every 8th transition costs 1 water, every 16th — 1 food (fresh food first, then canned). There is a single transition counter, SWALK, and "every 8th" is a mask:

Every 8th: SWALK AND #7 = 0

bit
7
6
5
4
3
2
1
0
SWALK = 23
0
0
0
1
0
1
1
1
23
AND #7
0
0
0
0
0
1
1
1
=
0
0
0
0
0
1
1
1
7 not 0 — no water used
SWALK = 24
0
0
0
1
1
0
0
0
24
AND #7
0
0
0
0
0
1
1
1
=
0
0
0
0
0
0
0
0
0 0 — every 8th: −1 water

The three low bits of a number are the remainder of division by 8. They are zero exactly at 8, 16, 24… With mask 15 — every 16th. As with the die, this works only for powers of two: SUP_WATER-1 with 8 gives the mask 7 = 111, but with 10 it would give 9 = 1001, and the count would become uneven.

Nothing to drink or eat — "THIRSTY" / "HUNGRY" and −1 health. If health runs out this way — "YOU COLLAPSE": cargo is lost, health is back to 9. The bottom of the HUD shows it all the time: "HEALTH 9 W2 F3" — health, water, food (HUD_HP, row 23).

CMB_SAY: the stack as a temporary shelf

The message "THE RAIDER IS DOWN!" is assembled from three pieces: "THE ", the type name from the TXT_NPC table, and a tail — a phrase number. The tail number arrives in A, but A is needed to print the first two pieces. The solution is to push it onto the stack and pull it at the end:

CMB_SAY:
        PHA                     ; tail number — onto the stack
        JSR MSG_CLEAR
        ...                     ; "THE ", type name — A is busy
        PLA                     ; tail number — off the stack
        JSR PUT_MSG
        JMP HUD_COPY

Other subroutines are called between PHA and PLA, and that is safe: every JSR pushes its return address on top of the stack and removes it with its own RTS. The stack is a pile: what goes on last comes off first. The only rule is exactly one PLA for every PHA.

Chapter 11. Status and the I window

What the hero means to this world is a single number: the status points STPTS, 0–255. A rank is derived from it, from RAIDER (looter) up to LEGEND (the one who turned the lights back on). Next to it sits reputation with three groups — guards, raiders and residents — a value of 0–15 per group. All of this is shown in the window opened by the I key.

Status window: HELPER (118), NEXT AT 128, health, money, gear, reputation bars
The I window: status HELPER (118 points), next rank from 128. Below: health, money, gear, parts, reputation bars and statistics.

Rank = points / 32

Eight ranks, 256 points — 32 points per rank. Dividing by 32 is five right shifts: 32 = 2⁵.

118 points → rank 3 (HELPER)

bit
7
6
5
4
3
2
1
0
STPTS
0
1
1
1
0
1
1
0
118
5 × LSR
0
0
0
0
0
0
1
1
3 the top 3 bits are the rank: 3 — HELPER
STPTS
0
1
1
1
0
1
1
0
118
AND #%11100000
1
1
1
0
0
0
0
0
96 start of the current rank
ADC #32
1
0
0
0
0
0
0
0
128 "NEXT AT 128" — start of the next one

Both lines of the window — "HELPER (118)" and "NEXT AT 128" — come from one byte. The rank is its top three bits. The next threshold is the same three bits with the low bits cleared (the start of the current rank) plus 32. The low 5 bits are "how much has been earned within the rank".

0–3132–6364–9596–127128–159160–191192–223224–255
0
RAIDER
1
STRANGER
2
NEIGHBOUR
3
HELPER
4
PILLAR
5
MAYOR
6
HERO
7
LEGEND

The rank word again comes from a table of string addresses (TXT_RANKS, in hidden memory): rank × 2 → address → HUD_PUTS. The number is produced by five LSRs, and the multiplication by 2 by a single ASL right after them.

What moves the status

ActionPointsWhere in the code
sold a settlement goods it needs — per item+1MKT_SELL (chapter 9)
settlement grew+8MKT_SELL
tied up a raider+2CMB_LOOT (chapter 10)
started a substation+16SUB_START (chapter 12)
hit a resident or a guard in front of witnesses−2CMB_WITNESS
killed−16CMB_SHOOT

The start is 32 points, STRANGER. From 64 (NEIGHBOUR) the hero is admitted to developed markets and the guards stop getting angry (CMB_GUARDH: +2 to a guard's hostility while the status is below 64). Starting a substation requires 160 (MAYOR).

PTS_ADD: the HERO ceiling

PTS_ADD:
        CLC
        ADC STPTS
        BCS @cap                ; went past 255
        CMP #PTS_CAP+1          ; more than 223?
        BCC @ok
@cap:
        LDA #PTS_CAP            ; 223 — top of the HERO rank
@ok:
        STA STPTS
        RTS

Two limits in a row. First, the carry: 220 + 16 = 236 fits in a byte, but 250 + 16 = 266 does not — ADC yields 10 with C = 1. Without the C check the hero would drop from HERO to RAIDER. Then the ceiling of 223: selling and tying up raiders cannot make anyone a LEGEND. Rank 7 (224–255) is reached only in the finale, when FINALE writes 255 directly (chapter 15).

PTS_SUB is the mirror image: SEC / SBC, and if C = 0 (went below zero) — 0. The same "not below zero" as for reputation in chapter 10.

Reputation: REP_INC without CLC

REP_INC:                        ; Y = group 0–2
        LDA REPS,Y
        CMP #15
        BCS @r                  ; already 15 — does not grow
        ADC #1                  ; C = 0 after CMP < 15 — no CLC needed
        STA REPS,Y
@r:
        RTS

Another case of "the flag is already set as needed". If execution reaches ADC, then BCS did not branch, so C = 0 — and there is no reason to write CLC. One byte and two cycles saved; the game code has dozens of such spots, and they are worth recognizing on sight.

Three groups are three consecutive bytes (REPS: guards, raiders, residents); the group number arrives in Y. The TGRP table from chapter 7 tells which group an NPC type belongs to.

INF_SHOW: the window and the bars

The I window is a full text screen, like the market: TXTSET, HOME, lines placed via MKT_AT (cursor to the start of line A). Almost everything is made of familiar pieces: a phrase by number, a number via PR_A0, a word from a table. The only new part is the reputation bars — 15 cells, "#" for each point and "." for the rest:

        LDY #0                  ; cell 0–14
@bar:
        LDA #$A3                ; "#"
        CPY MTMP                ; cell < reputation?
        BCC @b
        LDA #$AE                ; otherwise "."
@b:
        JSR COUT
        INY
        CPY #15
        BNE @bar

The "load one option, overwrite it if a condition holds" technique (like the pocket in chapter 10). Guards with reputation 11: cells 0–10 are "#", 11–14 are ".": ###########..... Exactly as in the screenshot.

Exit is Space, Esc or I again: SCR_BACK (chapter 9) restores the graphics and reprints the HUD.

Chapter 12. Substation and black start

The goal of the game. Each region has one substation. Bring a transformer, a cable and a relay, 10 cans of fuel, earn the MAYOR status — press S, and the region gets power. This is how the Spanish grid was brought back in 2025: a "black start", substation after substation. When all eight are lit — the finale.

SUB_INIT: where the substation is

The substation's location is not stored either — it is one byte of the seed. It takes the high byte S3 of location 0, the eighth byte of the seed table (chapter 1):

SUB_INIT:
        LDA WLD_TAB+7            ; location 0, byte 7
        CMP #$37
        BNE @ok
        EOR #%10000000          ; same as the start — move to the other half of the map
@ok:
        STA SUBLOC
        RTS

For Catalonia this is $1F — row 1, column 15, the top right edge of the map. A location number is a byte 0–255, so any byte works as a place. One safeguard: if the value is $37 — the game's starting location — the substation moves with EOR #$80:

$37 → $B7: flipping bit 7 = +8 rows

bit
7
6
5
4
3
2
1
0
$37
0
0
1
1
0
1
1
1
EOR #$80
1
0
0
0
0
0
0
0
= $B7
1
0
1
1
0
1
1
1
row 3 → 11, same column

Bit 7 of the number is the top bit of the row (chapter 1: the row is the top 4 bits). Flipping it moves 8 rows, into the other half of the map. The substation is guaranteed to be far from the start.

The substation location is special. On load, SUB_LOC clears all of its screen roles — there are no settlements there, all 9 screens are outskirts. And SUB_GEN, at the end of building a screen, places a 6 × 3 yard stamp on screen 4 — pylons, wires, transformers, generators, a mesh fence. At cell 12, 5: row 4 and column 10 stay free for roads, as in every template (chapter 3).

ST_SUBST:
        .byte 6, 3
        .byte T_PYLON, T_WIRES, T_WIRES, T_WIRES, T_WIRES, T_PYLON
        .byte T_MESH_FENCE, T_TRANSFORMER, T_GENERATOR, T_TRANSFORMER, T_GENERATOR, T_MESH_FENCE
        .byte T_MESH_FENCE, T_GRAVEL, T_GRAVEL, T_GRAVEL, T_GRAVEL, T_MESH_FENCE
ST_SUBLIT:                      ; with power: lamps instead of pylons
        .byte 6, 3
        .byte T_LAMP, T_WIRES, T_WIRES, T_WIRES, T_WIRES, T_LAMP
        ...

Two stamps of the same shape — a dark one and a lit one. Which one to place is decided by a single bit (below). Both have the same walkability, so after the start the hero does not have to move anywhere.

SUB_OK: "is everything ready" as one flag

SUB_OK:
        LDX #2                  ; parts: one of each kind
@p:
        LDA PARTS,X
        BEQ @no                 ; one is missing — not allowed
        DEX
        BPL @p
        LDA BAG+3               ; fuel
        CMP #SUB_FUEL
        BCC @no                 ; less than 10 — not allowed
        LDA STPTS               ; status at least MAYOR …
        CMP #ST_MAYOR
        RTS                     ; … the answer is C straight from CMP
@no:
        CLC
        RTS

The last check does not branch at all: CMP #160 itself sets C = 1 if the status is ≥ 160 — and that is exactly the subroutine's "yes" answer. The comparison becomes the result. The same trick appears in the substation window: LDA PARTS,X / CMP #1 / JSR SUB_MARK — SUB_MARK prints "OK" if C = 1 (at least one present) and "--" otherwise.

Substation window: TRANSFORMER 1/1 OK, CABLE 1/1 OK, RELAY 1/1 OK, FUEL 10/10 OK, STATUS MAYOR OK, S - BLACK START
Everything is ready: "OK" next to each condition, "S - BLACK START" at the bottom.

Power by region: one byte for 8 regions

Where the lights are on is stored in the LIT byte: one bit per region. The current region has "its own bit" RBIT — 1, 2, 4 … 128 (the REG_BITS table, chapter 14).

LIT: power in Catalonia and Aragon

bit
7
6
5
4
3
2
1
0
LIT
0
0
0
0
0
0
1
1
$03 bit 0 — CATALONIA, bit 1 — ARAGON
LDA LIT / AND RBIT
0
0
0
0
0
0
1
0
hero in Aragon: RBIT = 2
=
0
0
0
0
0
0
1
0
$02 not 0 → power is on here: lit yard
LIT ORA RBIT
0
0
0
0
0
1
1
1
$07 start in the Basque Country (RBIT = 4)

"Is there power here" is AND RBIT, "turn the power on here" is ORA RBIT, "is it lit everywhere" is CMP #$FF: all 8 bits. One byte for the whole goal of the game.

SUB_START: what the start does

  1. The parts and fuel are used up: DEC PARTS,X × 3, fuel −10.
  2. Power: LIT ORA RBIT.
  3. Status +16.
  4. Every settlement in all 256 locations of the region gets +1 growth. The power is back — the whole region comes alive.
  5. If LIT has become $FF, all eight are lit: JMP FINALE.

Step 4 is a loop over X from 0 to 255 (INX / BNE — after 255 comes 0, chapter 1), and in each location there are three growth "nibbles" from chapter 9. Each has its own limit:

        LDA LOC_GROW,X          ; settlement 1 — low 4 bits
        AND #%00001111
        CMP #15
        BCS @s2                 ; already 15 — leave it, otherwise +1 spills into the high half
        INC LOC_GROW,X
@s2:
        LDA LOC_GROW,X          ; settlement 2 — high bits
        CMP #$F0
        BCS @s3                 ; already 15 — +16 would overflow the byte
        CLC
        ADC #16
        STA LOC_GROW,X

Why is a limit needed here but not in chapter 9? There, growth is only triggered while the level is below 7. Here everything grows at once, and a nibble that has reached 15 would, without a check, "spill over" into the neighbouring half of the byte — into another settlement's growth. The low half is checked on its own (AND #15); for the high half it is enough to compare the whole byte with $F0: a high half of 15 means the byte is at least $F0.

Lit substation yard, THE GRID IS ALIVE! CATALONIA HAS LIGHT
After the start: the screen is rebuilt with the lit stamp and lamps; the HUD shows "THE GRID IS ALIVE! CATALONIA HAS LIGHT".

When the window is closed after the start, the game rebuilds the screen (SCR_GEN): SUB_GEN now sees the power and places the stamp with lamps, and the grown settlements are rebuilt from their templates (chapters 3, 9).

Chapter 13. Map and fog

Return on a screen opens the region map: 16 × 16 cells, one cell per location. But not all of it is visible: only the cells the hero has visited, and their neighbours. The rest is empty — "fog". The map is also a way to travel: by bicycle or motorbike, straight to a known cell nearby. And a cheat from Doom is hidden here as well.

Region map: symbols of known cells, @ is the hero, * is the substation, the name and type of the cell under the cursor at the bottom
The map: "@" is the hero, "*" the substation, "!" anarchy, "." rural, "+" industrial, "#" developed. At the bottom — the cell under the cursor (inverse).

The map is text

The map is not drawn in HiRes: it is a text screen, one character per cell. Location n sits in row n / 16, column n AND 15 — the same number layout as in chapter 1. Placing the cursor on a cell is MAP_GOTO:

MAP_GOTO:
        STA MAPT
        LSR A                   ; row = n / 16
        LSR A
        LSR A
        LSR A
        STA CV
        JSR VTAB                ; BASL = row address (chapter 8)
        LDA MAPT
        AND #%00001111          ; column = n AND 15
        STA CH
        RTS

The type symbol comes from the string MAP_SYM: .asc "!.+#": type 0–3 (bits 0–1 of the high byte S0) is directly the character's index in the string. The type is fetched via WLD_BYTE — a single seed byte from the table, without copying all 8 into SEED: the map has 256 cells, and the saving is noticeable.

Fog: the "been here" bit

Every location has bit 6 in LOC_SRCH — "been here" (SEEN). It is set by MAP_BEEN every time the location is loaded, with a single ORA #SEEN. Bits 0–5 of the same byte mean "searched" (chapter 9).

A cell is visible if "been here" is set on the cell itself or on any of its four neighbours. MAP_SEE checks five bytes and finds the neighbours with the familiar WLD_RIGHT / LEFT / UP / DOWN — with their honest "C = 1 — edge of the map, no neighbour" (chapter 1):

        TAX
        LDA LOC_SRCH,X          ; the cell itself
        AND #SEEN
        BNE @yes
        TXA
        JSR WLD_RIGHT           ; right neighbour
        BCS @l                  ; edge — none, go to the next one
        TAX
        LDA LOC_SRCH,X
        AND #SEEN
        BNE @yes
        ...

MAP_FOG walks through all 256 cells once: if visible, it prints the symbol; if not, it leaves the cell alone (after HOME there is a space there anyway).

The substation is always visible: "*" is printed separately, after the fog. On top goes "@" where the hero is: LDA #$40 — "@" in flashing mode (chapter 8: bits 7–6 = 01). Before that, MAP_MARK remembers which character was in the cell, so it can be restored later.

The view cursor: inverse with one AND

The arrow keys on the map move the view cursor. The cursor is the same cell, only inverse: the character's two top bits are cleared.

"+" → inverse "+"

bit
7
6
5
4
3
2
1
0
character "+"
1
0
1
0
1
0
1
1
$AB
AND #%00111111
0
0
1
1
1
1
1
1
= inverse
0
0
1
0
1
0
1
1
$2B bits 7–6 = 00 — dark "+" on light

The previous character is saved in MCURU and restored when the cursor moves away (CUR_OFF). The character is read and written directly in screen memory — LDA (BASL),Y / STA (BASL),Y with Y = column: BASL is the row address set by VTAB. No COUT — it would move the cursor.

Below the map is the description of the cell under the cursor (MV_INFO): name (chapter 2), type and order, and the note "YOU ARE HERE" / "SUBSTATION" / "BEEN HERE". For an invisible cell — only "UNKNOWN". The name and type need the cell's seed — WLD_GET puts it into SEED. That is why, when leaving the map, the game puts the seed of the current location back into SEED: the map has "spoiled" it.

Keys are awaited by KEY_WAIT — a small loop of its own, LDA KBD / BPL, instead of the ROM's RDKEY: that one shows a flashing cursor, which the map does not need.

Transport: distance "by the longer side"

With a bicycle the hero can travel to any known cell at a distance of up to 5, with a motorbike up to 10. The distance is the larger of the two differences, in columns and in rows (the way a king moves in chess: a diagonal step also counts as one):

0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
0
00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
1
10
11
12
13
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F
2
20
21
22
23
24
25
26
27
28
29
2A
2B
2C
2D
2E
2F
3
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
4
40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
5
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
6
60
61
62
63
64
65
66
67
68
69
6A
6B
6C
6D
6E
6F
7
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
8
80
81
82
83
84
85
86
87
88
89
8A
8B
8C
8D
8E
8F
9
90
91
92
93
94
95
96
97
98
99
9A
9B
9C
9D
9E
9F
A
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B
B0
B1
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF
C
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E
E0
E1
E2
E3
E4
E5
E6
E7
E8
E9
EA
EB
EC
ED
EE
EF
F
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
$37 → $3C: columns |7 − 12| = 5, rows 0 → distance 5. Green — all cells at distance ≤ 5: an 11 × 11 square around the hero.
TRV_DIST:
        LDA MCUR                ; target column
        AND #%00001111
        STA TDIST
        LDA HERE                ; hero column
        AND #%00001111
        SEC
        SBC TDIST
        JSR ABSC                ; |difference| (chapter 7)
        STA TDIST
        ...                     ; the same for rows (4 × LSR)
        CMP TDIST
        BCC @r                  ; rows are closer — keep the columns
        STA TDIST               ; otherwise — the rows

The motorbike uses fuel: (cells + 2) / 3 — one can per 3 cells, rounded up. The processor cannot divide by 3, so the code subtracts 3 while it can and counts:

        CLC
        ADC #2                  ; distance + 2
        LDX #0
@div:
        CMP #3
        BCC @d                  ; less than 3 — done
        SBC #3                  ; C = 1 after CMP — no SEC needed
        INX                     ; one more can
        BNE @div
@d:
        STX TNEED

7 cells: 7 + 2 = 9 → 6 → 3 → 0, three subtractions — 3 cans. The "+ 2" before the division is what rounds up: 7 / 3 = 2.33 → 3. This is the same division by subtraction as the number printing in chapter 9, only with a single divisor. Instead of fuel, the bicycle uses water and food — as if the hero had walked that many screens (SUP_STEP in a loop).

On arrival — LOC_ENTER: the location, screen 4, the hero on a free spot. This is the same sequence as @enter in the main loop (chapter 0), only moved into a subroutine: both travel and the hyperjump between regions use it (chapter 14).

IDKFA: a cheat with memory

Typing I-D-K-F-A on the map gives +250 €. As in Doom, only money instead of weapons. The CHEAT subroutine receives every map key and remembers how many letters of the word have been typed so far (CHT, 0–4):

CHEAT:
        PHA                     ; the key is returned unchanged
        AND #%11011111          ; lowercase → uppercase
        LDX CHT
        CMP TXT_IDKFA,X         ; the expected letter?
        BEQ @next
        LDX #0                  ; no — start over;
        CMP TXT_IDKFA           ; but it might be "I" — a fresh start
        BNE @put
@next:
        INX
        CPX #5                  ; all 5 letters — +250 €
        ...

Lowercase → uppercase: clear bit 5

bit
7
6
5
4
3
2
1
0
"i"
1
1
1
0
1
0
0
1
$E9
AND #%11011111
1
1
0
1
1
1
1
1
= "I"
1
1
0
0
1
0
0
1
$C9

In ASCII a lowercase letter differs from the uppercase one by exactly bit 5: "I" = $C9, "i" = $E9. Clear it, and case no longer matters. The arrow keys and Return already have bit 5 = 0, so they are not affected. The same technique is used in the menu (chapter 15).

A small detail is "what if it is I". Suppose "I-D-I-D-K-F-A" is typed: at the third letter "K" was expected, "I" arrived — the counter resets to 0. But this "I" may itself be the start of the word. So after the reset it is compared once more with the first letter — and if it matches, the counter becomes 1, not 0. Without this check the cheat would not accept such a string.

The money is added as a 16-bit value capped at $FFFF (chapter 9), and the key is restored from the stack (PLA) — the map receives it untouched and handles it as usual.

Chapter 14. Regions and disk

Spain is 8 regions in a 3 × 3 grid laid out "as on the map": the Basque Country, Aragon and Catalonia at the top, Castile, Madrid and Valencia in the middle, Andalusia and Murcia at the bottom. Each has its own seed (chapter 1) — its own 256 locations. Only one region fits in memory, so on leaving, the game writes everything that changed in it to the disk, and on returning reads it back. This chapter covers neighbours, moving between regions and working with the disk directly from the program.

2BASQUEbit 2 = 4
1ARAGONbit 1 = 2
0CATALONIAbit 0 = 1
3CASTILEbit 3 = 8
4MADRIDbit 4 = 16
5VALENCIAbit 5 = 32
6ANDALUSIAbit 6 = 64
7MURCIAbit 7 = 128
sea

Where a region sits in the grid is given by two tables, REG_COL and REG_ROW. Which region neighbours it on which side is the REG_NEIGH table, 4 bytes per region (↑ → ↓ ←); $FF means sea or border:

REG_NEIGH:                      ; ↑ → ↓ ←
        .byte $FF, $FF, 5, 1    ; 0 CATALONIA: down — Valencia, left — Aragon
        .byte $FF, 0, 4, 2      ; 1 ARAGON
        ...
        .byte 4, $FF, $FF, 6    ; 7 MURCIA

The index into the table is region × 4 + side (ASL ASL / ADC HDIR). The side is the same direction number ↑0 →1 ↓2 ←3 used everywhere in the game.

Three bit-set bytes describe all 8 regions at once, one bit per region (the REG_BITS table: 1, 2, 4 … 128): RBIT is the bit of the current region, RVISIT marks where the hero has already been, LIT where the lights are on (chapter 12). In the diagram above Catalonia and Aragon are highlighted — RVISIT = %00000011 = 3.

REG_EDGE: across the region border

From chapter 6: the hero walked off the edge of a screen, WALK_* reported "edge of the region" — control passes to REG_EDGE. It requires a neighbour on that side (not sea), a motorbike and 5 cans of fuel. If all are present, the hero appears in the neighbouring region at the opposite edge, in the same row or the same column. The new location is computed with two masks:

Catalonia $30, left → Aragon $3F

bit
7
6
5
4
3
2
1
0
HERE
0
0
1
1
0
0
0
0
$30 row 3, column 0 — left edge
AND REG_KEEP[←]
1
1
1
1
0
0
0
0
$F0 left: the row is kept
=
0
0
1
1
0
0
0
0
$30
ORA REG_EDGEL[←]
0
0
0
0
1
1
1
1
$0F … and the column becomes the right edge, 15
= new
0
0
1
1
1
1
1
1
$3F row 3, column 15 — in Aragon

REG_KEEP says which half of the number is kept ($F0 — the row, $0F — the column), REG_EDGEL which edge to write into the other half. For ↑: keep the column, set the row to the bottom one ($F0). Four directions — four pairs of masks in the tables, without a single "if".

The screen changes as in chapter 6 when crossing a location edge: left +2, right −2, up +6, down −6. In the REG_SCRD table "−2" is stored as 254 and "−6" as 250 — addition wraps around 256 (chapter 3).

REG_SWITCH: what happens when the region changes

  1. While the disk is in use — a text screen: "TRAVELLING TO ARAGON".
  2. REG_PUT: the three tables of the current region — LOC_SRCH, LOC_GROW, LOC_GROW3, 256 bytes each — are copied back to back into the buffer at $4000 and written to the disk as file REG0…REG7.
  3. Change REGION and RBIT; WLD_FILL — the new 256 seeds; SUB_INIT — the new substation.
  4. Has the hero been there before (RVISIT AND RBIT)? Then REG_GET reads its file back into the tables. If not, the tables are cleared and the bit is set in RVISIT.

That is the whole "world save": 768 bytes per region. Not a single location, screen or price is written — the seed will produce them again. Only what has changed during play goes to disk: what has been searched, where the hero has been, how much the settlements have grown, how many raiders have been tied up.

Why is the buffer at $4000? That is HiRes page 2. While the disk is in use, the screen shows text and the graphics are not needed — 8 KB of free memory. After the move, the new screen is redrawn from scratch anyway.

REG_DOS: a DOS command with the region digit

How a program asks DOS to write a file is covered in chapter 0: it prints Ctrl-D and the command text. What is new here is the region number in the file name. One template serves all eight:

TXT_BSAVE:      .asc "BSAVE REG#,A$4000,L$300"
                .byte 0
@c:
        LDA (STR),Y             ; template character
        BEQ @end
        CMP #$A3                ; "#"?
        BNE @p
        LDA REGION              ; → region digit
        ORA #$B0
@p:
        JSR COUT
        INY
        BNE @c

When "#" is encountered, REGION ORA #$B0 is printed instead (digit → character, chapter 6). For Aragon, DOS receives "BSAVE REG1,A$4000,L$300": write 768 bytes ($300) from address $4000 into file REG1. The same template with "#" is used to read the file (BLOAD REG#,A$4000).

REG_VIEW: overview of Spain and the hyperjump

R on the map shows an overview of the eight regions. On-screen positions are computed from the grid position: row = 3 + grid row × 5, column = grid column × 13. Again multiplication by shifts and additions: × 5 = × 4 + × 1, × 13 = × 8 + × 4 + × 1:

        LDA REG_COL,X           ; c
        ASL A
        ASL A                   ; 4c
        STA CH
        ASL A                   ; 8c
        ADC CH                  ; 12c
        ADC REG_COL,X           ; 13c
        STA CH

T in the overview is a hyperjump to a region already visited: 5 cans for each grid step (|Δ column| + |Δ row| — here not the "king" distance but ordinary steps along the sides), with a motorbike. The hero appears in the centre of the region — at location $77.

Chapter 15. Menu, saving, intro, LEGEND

The last chapter covers what surrounds the game: the intro shown at load time, the title menu, the pause screen with saving, continuing from the same spot, and the finale when all eight regions are lit.

TITLE: a menu from a table

Title menu: BLACKOUT, SPAIN YEARS LATER, N - NEW GAME, C - CONTINUE, Q - QUIT TO DOS
The title menu is five lines of text.

The five menu lines are not five pieces of code but a table of triples "row, column, message number", terminated by a zero:

TITLE_TAB:  .byte 4, 16, M_TBLACK,  6, 11, M_TSPAIN,  10, 12, M_TNEW,  12, 12, M_TCONT,  14, 12, M_TQUIT,  0
@l:
        STX MG
        LDA TITLE_TAB,X         ; row (0 = end of table)
        BEQ @key
        JSR MKT_AT              ; cursor to start of row
        LDX MG
        LDA TITLE_TAB+1,X
        STA CH                  ; column
        LDA TITLE_TAB+2,X
        JSR PUT_MSG             ; message (chapter 8)
        LDA MG
        CLC
        ADC #3                  ; next triple
        TAX
        BNE @l

Moving a menu line means changing one number in the table. This is the same "data instead of code" technique used by ROSTER, the settlement templates and SAVE_TAB below. Screen row 0 is not used by the menu, so 0 is free to mean "end".

The key goes through AND #%11011111 (lowercase → uppercase, chapter 13) and three comparisons. N gives CLC / RTS: "new game" (chapter 0: JSR TITLE / BCC @newgame). Q is JMP $03D0: the DOS "warm start" address — it exits to DOS with the "]" prompt without rebooting the machine. C tries to load a saved game.

Saving: HERO + REGn

Esc on the map opens the pause screen: S saves, Q quits, Return goes back. A save consists of two files:

Which variables are saved is again a table: "address, length" pairs, terminated by a zero.

SAVE_TAB:       .word BAG     ; backpack 16, parts 3, money 2
                .byte 21
                .word REPS    ; reputation with three groups
                .byte 3
                .word HP      ; health, gear
                .byte 2
                .word KILLS   ; kills, transitions, points, grown, tied up, substation, light
                .byte 7
                .word REGION  ; region, its bit, where visited
                .byte 3
                .word HX2     ; hero: x / 2, y
                .byte 2
                ...
                .word 0
                .byte 0

The variables sit in memory in scattered pieces rather than one block; the table gathers them together. 21 + 3 + 2 + 7 + 3 + 2 + 1 + 1 = 40 bytes plus the marker — it fits in 64.

SAVE_COPY: one subroutine for "there" and "back"

Saving means copying the variables into a buffer. Loading is the same thing in reverse. One subroutine does both, and the direction is passed in the carry flag (C = 0 — into the buffer, C = 1 — from the buffer). But inside, the carry flag gets clobbered by additions, so it has to be stored somewhere. How is a single bit saved?

SAVE_COPY:
        ROR MTMP                ; C → bit 7 of MTMP
        ...
@b:
        BIT MTMP                ; bit 7 → N flag
        BMI @in                 ; 1 = from buffer
        LDA (PTR),Y             ; 0 = to buffer:  variable →
        STA (PTR2),Y            ;                → buffer
        JMP @n
@in:
        LDA (PTR2),Y            ; buffer →
        STA (PTR),Y             ;   → variable

ROR puts the carry flag into bit 7

bit
7
6
5
4
3
2
1
0
MTMP (old value)
0
0
1
0
1
0
1
0
$2A
C = 1 (load)
0
0
0
0
0
0
0
1
ROR MTMP
1
0
0
1
0
1
0
1
$95 all bits shift right, C enters bit 7 (bit 0 goes to C)
BIT MTMP
1
0
0
1
0
1
0
1
bit 7 → N = 1 → BMI @in: "from buffer"

ROR is "rotate right": a right shift through the carry. The bit 0 that falls out goes into C, and the old C enters bit 7. Only bit 7 matters: it now holds the direction. The other bits are garbage, but nothing looks at them. Later in the loop BIT MTMP copies bit 7 into the N flag, and BMI decides. The carry flag, clobbered by the pointer additions, is no longer needed.

The pointer PTR points to the current variable from the table, PTR2 into the buffer, and after each piece it advances by that piece's length (16-bit, with a carry into the high byte — BCC / INC PTR2+1). The buffer is again $4000, the second graphics page (chapter 14).

GAME_LOAD: continuing from the same spot

C in the menu: BLOAD HERO,A$4000 and a check of the first byte — the marker SAVE_MARK = $C2 (the letter "B"). From the very start the disk holds an empty HERO file — 64 zeros. Until the player has saved at least once, there is no marker: CLC / RTS, and the menu prints "NO SAVED GAME". The file always exists, so DOS has nothing to complain about.

If the marker is present — SEC and SAVE_COPY in the reverse direction. Then the game rebuilds the world, just as when moving between regions and entering a screen: WLD_FILL (the region's seeds), SUB_INIT, REG_GET (its tables from disk), LOC_LOAD, SCR_GEN, NPCs — and the hero stands at the saved spot. Only 40 bytes are saved, yet the whole world is restored: everything else comes from the seed again.

FINALE: LEGEND

When LIT becomes $FF after a substation starts — all 8 regions are lit — SUB_START jumps to FINALE:

FINALE:
        LDA #255
        STA STPTS               ; status = LEGEND (chapter 11: only here)
        ...
        JSR REG_DOS             ; BLOAD LEGEND,A$2000 — picture straight into video memory
        STA TXTCLR              ; graphics …
        STA MIXCLR              ; … full screen, without the 4 text lines
        STA HIRES
        STA LOWSCR
        JSR KEY_WAIT
        STA MIXSET
        LDX #$FF                ; reset the stack
        TXS
        JMP start               ; as after launch: title menu
LEGEND: the hero by a map of Spain with a lit grid, THE LIGHTS ARE BACK ON. SPAIN IS ALIVE.
The finale: the LEGEND picture on the full screen.

The picture is the file LEGEND, exactly 8,192 bytes: the same HiRes page as in chapter 4, byte for byte. In the source it is legend.s — .org $2000 and 8,192 numbers in .byte lines. Not a single instruction, only data, stored exactly as the picture sits in memory. BLOAD puts it straight at address $2000, and the video circuitry shows it immediately.

LDX #$FF / TXS is a new instruction. TXS copies X into the stack pointer. The finale is called from deep inside: main loop → ACT_KEY → SUB_SHOW → SUB_START → FINALE, and the stack holds the return addresses of all these calls. There is no need to return there — the game starts over. A stack pointer of $FF means "stack empty", as right after power-on, and JMP start restarts everything without drowning in old addresses.

The intro: a separate program

The intro is a separate file INTRO (intro.s), launched by HELLO (chapter 0). It has the same address as the game, .org $6000: it runs, tells DOS BRUN MAIN, and the game loads on top of it. There are no pictures in its code — the 8 KB frames sit on the disk as files INTRO1…INTRO7, and the intro tells DOS where to load them. As in an animated film: while the viewer watches a frame on one page, the next one is already loading into the other.

IBERIA: the grid of Spain
INTRO1: the grid, 28 April 2025, 12:32
THE GRID WENT DOWN. BLACKOUT
INTRO3: BLACKOUT
Barcelona
INTRO4: Barcelona

6502 instruction reference

Everything the Apple II processor can do: 56 instructions, 3 registers and 7 flags. Here they are gathered in one place: what each instruction means, which flags it changes, an example from the BLACKOUT code and the chapter where it is covered in detail. The game uses 43 of the 56 instructions; the rest are marked.

Registers

RegisterBitsPurpose
A8accumulator: all computation (addition, logic, comparison) goes through it
X8index and counter: LDA TABLE,X, INX, CPX
Y8second index; the only one for pointers (PTR),Y
S8stack pointer: the stack is page $0100–$01FF, growing down from $01FF
PC16address of the next instruction; changed only by jumps, branches, JSR, RTS
P8flags — see below

Flag register P

bit
7
6
5
4
3
2
1
0
P
N
V
–
B
D
I
Z
C
FlagMeaningSet byRead by
Nnegative: a copy of bit 7 of the resultalmost everything that changes a register; BIT — bit 7 of memoryBMI, BPL
Voverflow: signed overflowADC, SBC; BIT — bit 6 of memoryBVC, BVS
Bbreak: marks a BRKBRKinterrupt handler
Ddecimal: decimal arithmeticSED, CLDADC, SBC
Iinterrupt: interrupts disabledSEI, CLIthe processor
Zzero: the result is zeroalmost everything that changes a register; CMP — "equal"BEQ, BNE
Ccarry: carry / "no borrow" / the bit shifted outADC, SBC, CMP, shifts, CLC, SECBCC, BCS, ADC, SBC, ROL, ROR

The main rule (chapter 0): flags live until the next instruction that changes them. STA, STX, STY, branches and JSR leave the flags alone, so they can be placed between a comparison and a branch.

Addressing modes — where an instruction gets its number

The same instruction (LDA) can take its number in ten ways. The mode is visible in the notation:

ModeNotationExample from the gameMeaningBytes
implied—INX, CLC, RTSeverything is clear from the instruction itself1
accumulatorAASL Aoperate on A1
immediate#numberLDA #$20, CMP #7the number itself is in the instruction2
zero pageaddress $00–$FFLDA SEED ($10)byte at a short address — one byte shorter and one cycle faster2
zero page,Xaddress,XSTA SEED,Xzero page address + X2
absoluteaddress $0000–$FFFFLDA KBD ($C000)byte at a full address3
absolute,X / ,Yaddress,XLDA TXT_BLOAD,Xaddress + X (or Y): a table element3
indirect indexed(pointer),YLDA (PTR),Ythe address sits in two zero page cells, plus Y2
relativelabelBNE @loopconditional branches only: offset −128…+1272
indexed indirect(pointer,X)not usedthe pointer is taken from the zero page at address + X2
indirectJMP (address)not usedjump to the address stored in memory3

16-bit addresses in the code are always stored low byte first: LDA TXT_BLOAD,X is BD 67 93 (chapter 0).

All 56 instructions

Load and store

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
LDALoaD AA ← number or memory byteN ZLDA SEED+1ch. 1
LDXLoaD XX ← …N ZLDX #0ch. 0
LDYLoaD YY ← …N ZLDY #0ch. 1
STASTore Amemory ← A—STA SEED,Xch. 1
STXSTore Xmemory ← X—STX TCXch. 4
STYSTore Ymemory ← Y—STY TCYch. 4

Register transfers

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
TAXTransfer A → XX ← AN ZASL A / TAXch. 2
TAYTransfer A → YY ← AN ZASL A ×3 / TAYch. 1
TXATransfer X → AA ← XN ZTXA / ADC #8 / TAXch. 7
TYATransfer Y → AA ← YN ZTYA / ASL Ach. 3
TSXTransfer S → XX ← stack pointerN Znot used
TXSTransfer X → Sstack pointer ← X—LDX #$FF / TXSch. 15

Stack

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
PHAPusH Apush A onto the stack—PHA … PLA in MSG_Nch. 8
PLAPuLl Apull from the stack into AN ZPLAch. 8
PHPPusH Ppush the flags onto the stack—not used
PLPPuLl Ppull the flags from the stackallnot used

Arithmetic

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
ADCADd with CarryA ← A + number + CN V Z CCLC / ADC SEED+2ch. 1
SBCSuBtract with CarryA ← A − number − (1 − C)N V Z CSEC / SBC #9ch. 3
INCINCrementmemory byte + 1N ZINC WCNTch. 1
DECDECrementmemory byte − 1N ZDEC GSCRch. 6
INXINcrement XX + 1N ZINXch. 0
INYINcrement YY + 1N ZINYch. 1
DEXDEcrement XX − 1N ZDEX / BPLch. 6
DEYDEcrement YY − 1N ZDEYch. 3

Logic

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
ANDANDA ← A AND number: 1 where both are 1N ZAND #%00000011ch. 1
ORAOR with AA ← A OR number: 1 if at least one is 1N ZORA #%00100000ch. 2
EORExclusive ORA ← A exclusive OR: 1 where the bits differN ZEOR SEED+3,Ych. 3
BITBIT testN ← bit 7 of the byte, V ← bit 6, Z ← (A AND byte) = 0; A unchangedN V ZBIT KBDSTRBch. 0

Comparison

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
CMPCoMPare AA − number, the result is discarded, only the flags remainN Z CCMP LASTKch. 0
CPXComPare XX − numberN Z CCPX #6ch. 1
CPYComPare YY − numberN Z CCPY #1ch. 9

Shifts

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
ASLArithmetic Shift Leftall bits left, bit 7 → C, 0 enters bit 0 (× 2)N Z CASL Ach. 1
LSRLogical Shift Rightall bits right, bit 0 → C, 0 enters bit 7 (/ 2)N Z CLSR Ach. 1
ROLROtate Leftleft, bit 7 → C, old C → bit 0N Z CROL PTR+1ch. 1
RORROtate Rightright, bit 0 → C, old C → bit 7N Z CROR MTMPch. 15

Jumps and subroutines

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
JMPJuMPjump to an address—JMP SCR_TILEch. 4
JSRJump to SubRoutinepush the return address and jump—JSR WLD_STEPch. 0
RTSReTurn from Subroutinepull the address from the stack and return—RTSch. 0
RTIReTurn from Interruptreturn from an interruptallnot used
BRKBReaKsoftware interruptB Inot used

Conditional branches (±127 bytes)

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
BEQBranch if EQualbranch if Z = 1 (equal, zero)—BEQ @walkch. 0
BNEBranch if Not Equalbranch if Z = 0—BNE @loopch. 0
BCCBranch if Carry Clearbranch if C = 0 (after CMP: less than)—BCC @stunch. 10
BCSBranch if Carry Setbranch if C = 1 (after CMP: greater or equal)—BCS @edgech. 5
BMIBranch if MInusbranch if N = 1 (bit 7 of the result)—BMI @newch. 0
BPLBranch if PLusbranch if N = 0—DEX / BPL @svch. 6
BVCBranch if oVerflow Clearbranch if V = 0—not used
BVSBranch if oVerflow Setbranch if V = 1—not used

Flags

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
CLCCLear CarryC ← 0 (before ADC)CCLCch. 1
SECSEt CarryC ← 1 (before SBC; "yes" as an answer)CSECch. 3
CLVCLear oVerflowV ← 0Vnot used
CLDCLear DecimalD ← 0: ordinary binary arithmeticDnot used
SEDSEt DecimalD ← 1: ADC / SBC in binary-coded decimalDnot used
CLICLear Interruptenable interruptsInot used
SEISEt Interruptdisable interruptsInot used

Other

InstructionFrom the wordsWhat it doesFlagsExample from the gameWhere
NOPNo OPerationdo nothing (1 byte, 2 cycles)—not used

Common techniques — where to find them

TaskHow it is doneWhere
add 16-bit numbersCLC / ADC low / ADC high — the carry propagates by itselfch. 1
16-bit "is it enough" comparisonCMP low / SBC #0 high / BCCch. 9
multiply by 2, 4, 8…ASL A (16-bit — ASL / ROL)ch. 1
multiply by 20, 6, 13shifts + addition: 20 = 16 + 4ch. 3, ch. 14
divide by 2, 4, 32LSR A the required number of timesch. 11
divide by 3, by 10subtract in a loop and countch. 9, ch. 13
remainder of division by 8, 16, 32AND #7 / #15 / #31ch. 10
extract a bit fieldLSR down to bit 0, then AND maskch. 1
set / clear / flip bitsORA / AND / EOR with a maskch. 0
absolute differenceSEC / SBC / BCS, otherwise EOR #$FF / ADC #1ch. 7
"not below zero", "not above 255"BCS after SBC; CMP #255 / BEQ before INCch. 10
"yes / no" answer from a subroutineSEC / CLC before RTS, caller uses BCS / BCCch. 0
select by numberaddress table: number × 2 → two bytesch. 2, ch. 8
loop over a table of recordsX += record size, CPX endch. 7
loop down to zeroDEX / BPL (with X ≤ 127)ch. 6
random numberASL / BCC / EOR #$1Dch. 3
subroutine call at the end — no returnJMP instead of JSR + RTS ("tail call")ch. 4
long conditional branchinverted condition around a JMPch. 6

The //c processor is a 65C02, which has a few more instructions (BRA, STZ, PHX, PLX, INC A…). BLACKOUT does not use them: the game uses only the original 6502 instructions, so the code also runs on the Apple ][+.


34 files, about 11,800 lines — and almost everywhere the same few techniques: a table instead of a formula, a mask instead of division, the C flag as an answer, a seed instead of storage. Every instruction that appears in the chapters is collected in the reference below.