Walkers that turn at walls and at each other, the way Mario's Goombas do
Two walkers of our own between two walls, with the square from the solid lesson beside them. Play it and watch them meet, turn, walk to the walls and back. The program is 415 instructions in 1,129 bytes, built and checked the same way.
Play it here Change it on the desk The cartridge, to play anywhere that plays NES cartridges: walkers.nes
On the screen
A walker needs only two rules
The Goombas in Super Mario Bros. move by two simple rules. They step half a pixel a frame, one pixel every second frame, and when one walks into a wall it turns round: for one frame it is a pixel inside the wall, then it is pushed back out and walks the other way. When two meet, both turn on the same frame, already overlapping a little, because the box the game checks is smaller than the picture. Our walkers keep the same pace, look the level up at their leading edge the way the square does, and turn as soon as they touch, so they are never seen inside a wall or overlapping.
| this cartridge | Super Mario Bros. | |
|---|---|---|
| pixels a step, and frames between steps | 1, every 2 | 1, every 2 |
| turns at walls seen | 4 | 3 |
| a frame spent a pixel inside the wall | no | yes |
| meetings seen, both turning on the same frame | 3 | 1 |
| pixels the two overlap when they turn | 0 | 7 |
As written
The part of the program this lesson is about. The whole program is a plain text file: walkers.s
;; The walkers, on every second frame: each takes its step, and if its
;; leading edge is then in a wall it goes back and turns. Then, if the one
;; on the left walks right and the one on the right walks left and they
;; touch (16 apart), both turn.
walkers:
LDA $44
EOR #$01
STA $44
BEQ resting
LDX #$00
JSR stride
LDX #$01
JSR stride
LDA $42
CMP #$01
BNE resting
LDA $43
CMP #$FF
BNE resting
SEC
LDA $41
SBC $40
CMP #$11
BCS resting
LDA #$FF
STA $42
LDA #$01
STA $43
resting:
RTS
;; Walker X: a step, and the block at its leading edge (its right edge
;; walking right, its left walking left), at its feet's height less one.
stride:
CLC
LDA $40,X
ADC $42,X
STA $40,X
LDY $42,X
CPY #$01
BNE leftward
CLC
ADC #$0F
leftward:
STA $20
LDA #$CF
STA $21
STX $26
JSR solid
LDX $26
CMP #$00
BEQ strode
SEC
LDA $40,X
SBC $42,X
STA $40,X
LDA #$00
SEC
SBC $42,X
STA $42,XBefore this one: Ground, a block and a wall, solid the way Mario's are