11 NES BASIC PROGRAMMING GUIDE
Controllers, input events and a game loop
JOY(1) samples held virtual NES buttons. The mask is A=1, B=2, Select=4, Start=8, Up=16, Down=32, Left=64, Right=128. Simultaneous buttons add. Read once into J if several tests should use the same sample. There is no bitwise AND, but integer arithmetic extracts a bit: J/128 is Right; J/16-J/32*2 is Up.
INKEY$ instead queues new press edges on port one. Codes are A=128, B=129, Select=130, Start=131, Up=132, Down=133, Left=134, Right=135. They are reserved codes, not ASCII. Held gameplay buttons do not repeat each frame. Simultaneous edges queue in that order. Eight events fit; overflow drops the newest and increments a saturating internal counter. RUN/focus/input transitions clear the queue; the Start that launches RUN is not also an input event.
10 K$=INKEY$
20 IF K$="" THEN GOTO 10
30 PRINT "CODE=";ASC(K$)
40 GOTO 10Press A while it runs: CODE=128 appears. An idle empty result loops before ASC, avoiding ASC(""). External keyboard text during RUN queues text bytes; it does not discover arbitrary USB/Bluetooth scan codes. The host or adapter maps a physical device to virtual NES buttons. Compatibility depends on that mapping.
Hold Select alone for 30 frames during RUN to open text keys. D-pad navigation then selects text rather than sending game-direction events. A sends the chosen character, B sends byte 8, Start sends byte 13, Select closes the keys. Short Select remains event 130. Start+Select is reserved for the emergency break. INPUT owns a separate edited-answer workflow, so do not expect it to consume these queued game events. After external-keyboard handshake, JOY(2) is zero.
10 SCREEN 1:X=80
20 SPRITE 0,X,100,0
30 J=JOY(1)
40 X=80+J/128*8
50 MOVE 0,X,100
60 WAIT 1:GOTO 30Hold Right: the ship moves from X=80 to X=88. Release Right: it returns to 80. This small complete game loop demonstrates sampling, changing state, MOVE and WAIT without leaving the valid coordinate range. It does not implement continuous acceleration. You can replace art 0 with an art ID you created, then save the modified source and artwork. Chapter 13 suggests safe extensions.