Skip to content

Latest commit

 

History

History
53 lines (36 loc) · 1.51 KB

File metadata and controls

53 lines (36 loc) · 1.51 KB

Random Number Generator

rust6502 exposes a simple random number generator trought a single memory-mapped register. It lets 6502 assembly programs get unpredictable values without the CPU having to implement its own pseudo-random algorithm.

Register

Address Name Access Description
$BFF3 RNG Read-only Returns a random byte (0x00-0xFF) on every read

Writes to this address is ignored.

How it works

From the 6502 program's point of view, $BFF3 behaves exactly like any other memory location: LDA $BFF3 loads a byte into $AC$ (Accumulator) and sets the Z/N flags as normal.

Because a new value is generated per read, reading it twice in a row will (almost always) give two differents bytes.

Example: random pixel color

This snippet fills the top row of the screen ($0200-$021F, 32 pixels) with random colors from the emulator's 16 color palette, by masking the random byte down to 4 bits (0x0F) so it always land on a valid palette index

.segment "CODE"

RESET:
    CLD
    LDX #$FF
    TXS

    LDX #$00

FILL_ROW:
    LDA $BFF3
    AND #$0F
    STA $0200, X
    INX
    CPX #32
    BNE FILL_ROW

LOOP:
    JMP LOOP

.segment "VECTORS"
    .word RESET
    .word RESET
    .word RESET

Tips

  • If you need a bigger range you can read $BFF3 twice and combine the bytes
  • If you need a specific rang (e.g 0-5 for a dice roll) you can read the byte, then use a loop or a modulo style comparison against your target range