Skip to content

Select the Nearest Active Target on NES

An enemy or homing projectile needs a target-selection rule that stays predictable when candidates tie.

An enemy or homing projectile needs a target-selection rule that stays predictable when candidates tie.

NES shows the working diagnostic row 01 05 00 01 03 00 00 64.
A completed native caller displays 01 05 00 01 03 00 00 64. The public field order below identifies these bytes; the capture is a state diagnostic, not a recording of a finished game.

Use it in a project

ACTIVE uses its low four bits for four candidates. Select the smallest Manhattan distance from unsigned byte ORIGIN_X/Y, breaking ties by lowest slot. Return a little-endian distance 0–510 and FOUND=1; no active targets returns SLOT=255, distance zero and FOUND=0. High ACTIVE bits are ignored.

Include component.inc once (MOS callers include the shared 6502 implementation through it). Reserve the public fields in this exact order: SLOT, DISTANCE_LO, DISTANCE_HI, FOUND, ACTIVE, ORIGIN_X, ORIGIN_Y, PX0, PX1, PX2, PX3, PY0, PY1, PY2, PY3. They occupy 15 contiguous bytes. Also reserve the private workspace: T0, T1, T2, T3, T4, T5, T6, T7 (8 bytes). Array names in the explanation refer to the numbered consecutive bindings, such as C0, C1 and so on.

Call nearest_target_init once at the intended reset boundary. It clears inputs as well as outputs and workspace. Set your starting state and configuration afterwards, then call nearest_target_step whenever the described event occurs. The helper reads no device, waits for no frame and installs no interrupt handler.

Ownership Fields
Retain between calls none
Supply before service ACTIVE, origin and candidate coordinates
Read after service SLOT, DISTANCE_LO/HI and FOUND

Compute two absolute coordinate differences and add them with a ninth bit. Replace the best candidate only for a strictly smaller distance, preserving the earlier slot on ties.

Reusable initialisation and service

6502.inc
; SPDX-License-Identifier: MIT
; Select the Nearest Active Target. See README.md for the byte interface and ownership.
; init clears the public fields and private workspace; set inputs afterwards.
nearest_target_init:
    lda #0
    sta SLOT
    sta DISTANCE_LO
    sta DISTANCE_HI
    sta FOUND
    sta ACTIVE
    sta ORIGIN_X
    sta ORIGIN_Y
    sta PX0
    sta PX1
    sta PX2
    sta PX3
    sta PY0
    sta PY1
    sta PY2
    sta PY3
    sta T0
    sta T1
    sta T2
    sta T3
    sta T4
    sta T5
    sta T6
    sta T7
    rts
nearest_target_step:
; SLOT = 255
    lda #255
    sta SLOT
; DISTANCE_LO = 0
    lda #0
    sta DISTANCE_LO
; DISTANCE_HI = 0
    lda #0
    sta DISTANCE_HI
; FOUND = 0
    lda #0
    sta FOUND
; T0 = 0
    lda #0
    sta T0
; T1 = 1
    lda #1
    sta T1
; while T0 < 4:
nearest_target_L1:
    lda T0
    cmp #4
    bcc nearest_target_L4
nearest_target_L5:
    jmp nearest_target_L3
nearest_target_L4:
    jmp nearest_target_L2
nearest_target_L2:
; T2 = ACTIVE & T1
    lda ACTIVE
    and T1
    sta T2
; if T2 != 0:
    lda T2
    cmp #0
    bne nearest_target_L9
nearest_target_L10:
    jmp nearest_target_L7
nearest_target_L9:
    jmp nearest_target_L6
nearest_target_L6:
; T2 = PX[T0]
    ldx T0
    lda PX0,x
    sta T2
; if T2 >= ORIGIN_X:
    lda T2
    cmp ORIGIN_X
    bcs nearest_target_L14
nearest_target_L15:
    jmp nearest_target_L12
nearest_target_L14:
    jmp nearest_target_L11
nearest_target_L11:
; T3 = T2 - ORIGIN_X
    lda T2
    sec
    sbc ORIGIN_X
    sta T3
    jmp nearest_target_L13
nearest_target_L12:
; T3 = ORIGIN_X - T2
    lda ORIGIN_X
    sec
    sbc T2
    sta T3
nearest_target_L13:
; T2 = PY[T0]
    ldx T0
    lda PY0,x
    sta T2
; if T2 >= ORIGIN_Y:
    lda T2
    cmp ORIGIN_Y
    bcs nearest_target_L19
nearest_target_L20:
    jmp nearest_target_L17
nearest_target_L19:
    jmp nearest_target_L16
nearest_target_L16:
; T4 = T2 - ORIGIN_Y
    lda T2
    sec
    sbc ORIGIN_Y
    sta T4
    jmp nearest_target_L18
nearest_target_L17:
; T4 = ORIGIN_Y - T2
    lda ORIGIN_Y
    sec
    sbc T2
    sta T4
nearest_target_L18:
; T5 = T3 + T4
    lda T3
    clc
    adc T4
    sta T5
; T6 = 0
    lda #0
    sta T6
; if T5 < T3:
    lda T5
    cmp T3
    bcc nearest_target_L24
nearest_target_L25:
    jmp nearest_target_L22
nearest_target_L24:
    jmp nearest_target_L21
nearest_target_L21:
; T6 = 1
    lda #1
    sta T6
    jmp nearest_target_L23
nearest_target_L22:
nearest_target_L23:
; T7 = 0
    lda #0
    sta T7
; if FOUND == 0:
    lda FOUND
    cmp #0
    beq nearest_target_L29
nearest_target_L30:
    jmp nearest_target_L27
nearest_target_L29:
    jmp nearest_target_L26
nearest_target_L26:
; T7 = 1
    lda #1
    sta T7
    jmp nearest_target_L28
nearest_target_L27:
nearest_target_L28:
; if T6 < DISTANCE_HI:
    lda T6
    cmp DISTANCE_HI
    bcc nearest_target_L34
nearest_target_L35:
    jmp nearest_target_L32
nearest_target_L34:
    jmp nearest_target_L31
nearest_target_L31:
; T7 = 1
    lda #1
    sta T7
    jmp nearest_target_L33
nearest_target_L32:
nearest_target_L33:
; if T6 == DISTANCE_HI:
    lda T6
    cmp DISTANCE_HI
    beq nearest_target_L39
nearest_target_L40:
    jmp nearest_target_L37
nearest_target_L39:
    jmp nearest_target_L36
nearest_target_L36:
; if T5 < DISTANCE_LO:
    lda T5
    cmp DISTANCE_LO
    bcc nearest_target_L44
nearest_target_L45:
    jmp nearest_target_L42
nearest_target_L44:
    jmp nearest_target_L41
nearest_target_L41:
; T7 = 1
    lda #1
    sta T7
    jmp nearest_target_L43
nearest_target_L42:
nearest_target_L43:
    jmp nearest_target_L38
nearest_target_L37:
nearest_target_L38:
; if T7 != 0:
    lda T7
    cmp #0
    bne nearest_target_L49
nearest_target_L50:
    jmp nearest_target_L47
nearest_target_L49:
    jmp nearest_target_L46
nearest_target_L46:
; SLOT = T0
    lda T0
    sta SLOT
; DISTANCE_LO = T5
    lda T5
    sta DISTANCE_LO
; DISTANCE_HI = T6
    lda T6
    sta DISTANCE_HI
; FOUND = 1
    lda #1
    sta FOUND
    jmp nearest_target_L48
nearest_target_L47:
nearest_target_L48:
    jmp nearest_target_L8
nearest_target_L7:
nearest_target_L8:
; T0 = T0 + 1
    lda T0
    clc
    adc #1
    sta T0
; T1 = T1 << 1
    lda T1
    asl
    sta T1
    jmp nearest_target_L1
nearest_target_L3:
    rts
component_end:

Machine contract

A/X/status may change; Y is preserved. The 2A03 has no decimal arithmetic mode. A direct JSR needs two return-address stack bytes. The helper makes no nested calls and adds no other stack use. Its named scratch is private workspace, not a pointer, a ROM variable or shared zero-page space that the game may borrow concurrently. The samples use fixed symbol bindings. Scope or rename every label and binding, including the component_end measurement marker, and allocate a separate block for each independent instance. Different helpers can also use common field names, so combining them needs separate namespaces or explicitly renamed bindings. Give each block one mutation owner.

The NROM caller owns PPU setup and background display, with NMI and DMC disabled. Table and packet sizes are bounded to fit the cartridge caller and internal RAM; the helper owns no PPU registers.

Adapt the caller

demo.asm supplies the bindings and include order. exercise.inc first runs table cases, then a separate client retaining state between calls. A game can call the public step entry directly and remove the diagnostic packet and display. Do not copy the diagnostic’s hardware takeover into an existing game loop.

Build with make ASM198X=/path/to/asm198x. The Makefile produces normal, custom, deliberately wrong and repaired programs. Tools must already be installed; the sample downloads nothing.

Bindings and include order

demo.asm
.segment "HEADER"
.byte "NES",$1a,2,1,0,0,0,0,0,0,0,0,0,0
SLOT=$80
DISTANCE_LO=$81
DISTANCE_HI=$82
FOUND=$83
ACTIVE=$84
ORIGIN_X=$85
ORIGIN_Y=$86
PX0=$87
PX1=$88
PX2=$89
PX3=$8a
PY0=$8b
PY1=$8c
PY2=$8d
PY3=$8e
T0=$8f
T1=$90
T2=$91
T3=$92
T4=$93
T5=$94
T6=$95
T7=$96
STATE=$80
input_ptr=$70
cases_left=$72
ptr=$74
saved_y=$76
OUTPUT=$0200
preview=OUTPUT+1400
ready=OUTPUT+1408
CUSTOM=0
BROKEN=0
COYOTE_STEPS=4
BUFFER_STEPS=4
TEXT_CAP=8
PROPERTY_COUNT=16
STREAM_BYTES=13
CRC_POLY=7
.include "caller.inc"
.include "exercise.inc"
component_start:
.include "component.inc"
.include "data.inc"
.include "cases.inc"
code_end:
.segment "VECTORS"
.word nmi,reset,irq
.segment "CHARS"
.include "../../input/controller-reading/edges-font.inc"
.res 8192-272,0

A client retaining state between calls

exercise.inc, excerpt
preview_rules:
.if CUSTOM
; ACTIVE = 9
    lda #9
    sta ACTIVE
; ORIGIN_X = 255
    lda #255
    sta ORIGIN_X
; ORIGIN_Y = 255
    lda #255
    sta ORIGIN_Y
; PX0 = 0
    lda #0
    sta PX0
; PY0 = 0
    lda #0
    sta PY0
; PX3 = 254
    lda #254
    sta PX3
; PY3 = 255
    lda #255
    sta PY3
.if BROKEN
; ACTIVE = 1
    lda #1
    sta ACTIVE
.endif
    jsr checked_step
    jsr emit_state
    rts
.else
; ACTIVE = 3
    lda #3
    sta ACTIVE
; PX0 = 100
    lda #100
    sta PX0
; PY0 = 100
    lda #100
    sta PY0
; PX1 = 2
    lda #2
    sta PX1
; PY1 = 3
    lda #3
    sta PY1
.if BROKEN
; ACTIVE = 1
    lda #1
    sta ACTIVE
.endif
    jsr checked_step
    jsr emit_state
.endif
    rts

Customise it

Select near the far corner of the coordinate range. The maintained custom caller changes its inputs or client sequence rather than hiding a different implementation behind the same label. Compare every state of the two clients, not only their final display.

Custom client selection

custom.asm
.segment "HEADER"
.byte "NES",$1a,2,1,0,0,0,0,0,0,0,0,0,0
SLOT=$80
DISTANCE_LO=$81
DISTANCE_HI=$82
FOUND=$83
ACTIVE=$84
ORIGIN_X=$85
ORIGIN_Y=$86
PX0=$87
PX1=$88
PX2=$89
PX3=$8a
PY0=$8b
PY1=$8c
PY2=$8d
PY3=$8e
T0=$8f
T1=$90
T2=$91
T3=$92
T4=$93
T5=$94
T6=$95
T7=$96
STATE=$80
input_ptr=$70
cases_left=$72
ptr=$74
saved_y=$76
OUTPUT=$0200
preview=OUTPUT+1400
ready=OUTPUT+1408
CUSTOM=1
BROKEN=0
COYOTE_STEPS=2
BUFFER_STEPS=2
TEXT_CAP=4
PROPERTY_COUNT=16
STREAM_BYTES=13
CRC_POLY=49
.include "caller.inc"
.include "exercise.inc"
component_start:
.include "component.inc"
.include "data.inc"
.include "cases.inc"
code_end:
.segment "VECTORS"
.word nmi,reset,irq
.segment "CHARS"
.include "../../input/controller-reading/edges-font.inc"
.res 8192-272,0

The custom diagnostic row is 03 01 00 01 09 FF FF 00. The full client trace in the source explains how it gets there.

Mistake and repair

The wrong caller only marks slot zero active, excluding a nearer candidate. Pass the actual occupancy mask and check FOUND before using SLOT.

The BROKEN branch lives in the sequential client, not the reusable helper. wrong.asm selects it; repaired.asm restores the normal call sequence. The repaired executable matches the normal program (for Spectrum, compare loaded CODE rather than the tape filename).

Select the deliberately wrong client

wrong.asm
.segment "HEADER"
.byte "NES",$1a,2,1,0,0,0,0,0,0,0,0,0,0
SLOT=$80
DISTANCE_LO=$81
DISTANCE_HI=$82
FOUND=$83
ACTIVE=$84
ORIGIN_X=$85
ORIGIN_Y=$86
PX0=$87
PX1=$88
PX2=$89
PX3=$8a
PY0=$8b
PY1=$8c
PY2=$8d
PY3=$8e
T0=$8f
T1=$90
T2=$91
T3=$92
T4=$93
T5=$94
T6=$95
T7=$96
STATE=$80
input_ptr=$70
cases_left=$72
ptr=$74
saved_y=$76
OUTPUT=$0200
preview=OUTPUT+1400
ready=OUTPUT+1408
CUSTOM=0
BROKEN=1
COYOTE_STEPS=4
BUFFER_STEPS=4
TEXT_CAP=8
PROPERTY_COUNT=16
STREAM_BYTES=13
CRC_POLY=7
.include "caller.inc"
.include "exercise.inc"
component_start:
.include "component.inc"
.include "data.inc"
.include "cases.inc"
code_end:
.segment "VECTORS"
.word nmi,reset,irq
.segment "CHARS"
.include "../../input/controller-reading/edges-font.inc"
.res 8192-272,0
NES shows the deliberate error row 00 C8 00 01 01 00 00 64.
The wrong client completes with 00 C8 00 01 01 00 00 64; its changed inputs and state explain the result.

Cost and alternatives

The measured helper extent is 329 code bytes; public state is 15 bytes and private scratch is 8 bytes. There are no immutable helper tables. Caller data, the test cases, return-address stack, alignment and display buffers cost additional space. These are assembled sizes, not cycle measurements.

Four candidates, no multiplication or square root. Squared Euclidean distance changes the selection and needs a wider sum.

Manhattan distance favours an axis-aligned metric, not circular Euclidean distance. It ignores walls and reachability.

Execution evidence

Four variants run on NTSC NROM, background only, DMC/NMI disabled, using Asm198x 0.0.72, Emu198x 0.44.2. Each executes 64 boundary/varied/error table cases, dirty initialisation and the separate retained-state client. An independent mathematical/container model checks every public byte after every call. This is bounded example coverage, not exhaustive correctness for every possible state.

The records retain loaded immutable code, completion, register sentinels, full packets, source/tool/firmware hashes and captures. The public gate validates these retained observations and rejects altered evidence; it does not run restricted firmware. No firmware is distributed. The eight displayed bytes are the first eight public fields, zero-padded when shorter; the packet includes every field.

Where it fits

Manhattan distance: The metric is part of the targeting behaviour, not merely an optimisation.

The Craft · Maths for Games · Source and native evidence.