Skip to content

Instantly share code, notes, and snippets.

@grendell
Last active August 18, 2023 22:35
Show Gist options
  • Save grendell/5c462074d8b3ef29e7c97b396e2286fb to your computer and use it in GitHub Desktop.
Save grendell/5c462074d8b3ef29e7c97b396e2286fb to your computer and use it in GitHub Desktop.
6502 Sneakiness
typedef struct {
uint8_t health;
// more fields
} enemy_t;
const int maxEnemies = 8;
enemy_t enemies[maxEnemies];
int isDead(enemy_t * enemy) {
return enemy->health == 0;
}
void updateEnemy(enemy_t * enemy) {
if (isDead(enemy)) {
return;
}
++enemy->health;
}
void update() {
for (int i = 0; i < maxEnemies; ++i) {
updateEnemy(enemies + i);
}
}
.segment "ZEROPAGE"
.struct enemy
health .byte
; more fields
.endstruct
maxEnemies = 8
enemies: .res maxEnemies * .sizeof(enemy) ; reserve space for 8 enemies
.segment "CODE"
.proc update
ldx #0
: jsr updateEnemy
txa ; advance x sizeof(enemy) bytes
clc
adc #.sizeof(enemy)
tax
cpx #maxEnemies * .sizeof(enemy) ; compare x with maxEnemies * sizeof(enemy)
bne :- ; if x != maxEnemies, loop
rts
.endproc
.proc isDead
lda enemies + enemy::health, x ; load enemy[x].health into accumulator
; here, x = index * sizeof(enemies)
beq dead ; compare with zero
alive:
lda #0 ; load accumulator with false
rts ; return
dead:
lda #1 ; load accumulator with true
rts ; return
.endproc
.proc updateEnemy
jsr isDead ; call isDead, expect result in accumulator
bne :+ ; branch if isDead, skip update
inc enemies + enemy::health, x
: rts
.endproc
.proc isDead
lda enemies + enemy::health, x ; load enemy[x].health into accumulator
; here, x = index * sizeof(enemies)
beq dead ; compare with zero
alive:
rts ; return
dead:
pla ; pull updateEnemy's 16-bit address off the stack,
pla ; so we return back to update
rts ; return
.endproc
.proc updateEnemy
jsr isDead ; call isDead, possibly return here
inc enemies + enemy::health, x
rts
.endproc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment