; *************************************************************************** ; *************************************************************************** ; ; random.asm ; ; Pseudo-random number generator (https://github.com/bbbradsmith/prng_6502) ; ; Copyright Brad Smith 2019. ; ; License: ; ; This code and may be used, reused, and modified for any purpose, commercial ; or non-commercial. ; ; Attribution in released binaries or documentation is appreciated but not ; required. ; ; *************************************************************************** ; *************************************************************************** ; ; This is a linear feedback shift register (LFSR) in Galois form, which is ; iterated 8 times to produce an 8-bit pseudo-random number. ; ; Two widths of LFSR are provided: ; ; 24-bit requires 3 bytes, and repeats after 16777215 calls. ; 32-bit requires 4 bytes, and repeats after 4294967295 calls. ; ; Usage: ; ; Initialize the zero-page "random" variable to any value other than 0. ; The size of "random" is 3 or 4 bytes, depending on the width of LFSR ; chosen. ; ; Call one of the RNG functions and an 8-bit result will be returned in the ; A-register (with flags), and the Y-register will be clobbered. ; ; Do not mix RNGs of different width in the same program, unless you can ; give them each separate "random" state storage. ; ; *************************************************************************** ; *************************************************************************** .ifndef _KICKC ; Variables defined in C? .zp random: .ds 4 ; Seed is 3 or 4 bytes. .code .endif _KICKC ; *************************************************************************** ; *************************************************************************** ; ; init_random - Initialize a 32-bit LFSR using an 8-bit seed value in Y. ; ; The LFSR is initialized to n'th entry of a standard CRC-32 lookup-table, ; which gives it a decent distribution of bits. ; ; Since seed is an 8-bit value, there are 255 (256-1) possible starting ; states for the LFSR, because 0 would generate a 0 state. ; ; CRC-32 code by Paul Guertin. See http://6502.org/source/integers/crc.htm ; init_random .proc lda #1 ; Init CRC-32 table value. sta >1 = %01100010) lda >1 = %00001101) lda