Newbie to SNES assembly, so pardon me if this is already well-known but: I wanted some random bytes for my game, but didn't really want to waste valuable CPU time with computing random bytes at runtime using an actual PRNG algorithm. I'm sharing my trick here in case it's helpful for others.
The gist is that I fill a ROM bank with random bytes using the assembler, and then call a GetRandomByte macro that fills A with the next random byte, and updates a pointer for the next time GetRandomByte is called. The code snippet is here:
This "wastes" an entire bank by filling it with random numbers, but I wasn't using that bank anyways (and if you wanted, you could easily change the code so that it only used 1024 bytes, or whatever.) You could also change it to be a subroutine instead of a macro, if you care more than I do about code size.
The gist is that I fill a ROM bank with random bytes using the assembler, and then call a GetRandomByte macro that fills A with the next random byte, and updates a pointer for the next time GetRandomByte is called. The code snippet is here:
Code:
.define randomBytePtr $1A ; Pick any free 2-byte address in your game's RAM.
; Stores result to A.
; Assumes 16-bit X & 8-bit A.
; Modifies X.
; Updates randomBytePtr.
.MACRO GetRandomByte
ldx randomBytePtr
lda $028000, X ; $028000: beginning of ROM bank 2.
inx
cpx #$8000 ; This is the size of the entire ROM bank.
bne +
ldx #0
+
stx randomBytePtr
.ENDM
; Fill an entire bank with random numbers.
.SEED 1
.BANK 2 SLOT 0
.ORG 0
.SECTION "RandomBytes"
.DBRND 32 * 1024, 0, 255
.ENDS
; Stores result to A.
; Assumes 16-bit X & 8-bit A.
; Modifies X.
; Updates randomBytePtr.
.MACRO GetRandomByte
ldx randomBytePtr
lda $028000, X ; $028000: beginning of ROM bank 2.
inx
cpx #$8000 ; This is the size of the entire ROM bank.
bne +
ldx #0
+
stx randomBytePtr
.ENDM
; Fill an entire bank with random numbers.
.SEED 1
.BANK 2 SLOT 0
.ORG 0
.SECTION "RandomBytes"
.DBRND 32 * 1024, 0, 255
.ENDS
This "wastes" an entire bank by filling it with random numbers, but I wasn't using that bank anyways (and if you wanted, you could easily change the code so that it only used 1024 bytes, or whatever.) You could also change it to be a subroutine instead of a macro, if you care more than I do about code size.