[stella] Random number generation on 2600

 Subject: [stella] Random number generation on 2600 From: emooney@xxxxxxxxxxxxxxxx (Erik Mooney) Date: Mon, 24 Mar 1997 21:02:50 GMT
```Being a computer science major, I'm interested in this random number
problem.. I don't like the approach of relying on the 2600's quasi-random
state at powerup, especially because that doesn't work on the emulators.
With some research, I found a few algorithms of the type:
Random(n) = (m*Random(n-1)+c) mod z, where m, c, and z are "magic" numbers
that give a sequence of 2^32 terms before it repeats.  Problem is, m tends
to be a number like 25173 that is difficult for the 6502 to manipulate, let
alone multiply by it. (my kingdom for a multiply instruction =) ).

I did find the following algorithm: it uses a 31-bit register initialized
to any nonzero value.  A random bit is generated by XORing bits 27 and 30
of the register, then shifting the entire thing one bit to the left and
placing the new bit on the right.  If you want a random byte, simply call
the algorithm eight times and read the lowest 8 bits of the register.  This
algorithm produces a sequence of (2^31 - 1) random bits before repeating.
To seed the register, you can generate one random bit every frame whether
you need it or not; then, your register can have at least 200 different
values by the time the user presses Reset.

Some code for the procedure:
;Rand1, Rand2, Rand3, Rand4 are RAM locations, initialized to any nonzero
;value at program start (I use \$6D)
;RandomBit generates one random bit.
;RandomByte generates one random byte and returns it in the accumulator.

RandomBit
lda rand4
asl
asl
asl
eor rand4 ;new bit is now in bit 6 of A
asl
asl        ;new bit is now in carry
rol rand1 ;shift new bit into bit 0 of register; bit 7 goes into carry
rol rand2 ;shift old bit 7 into bit 8, etc.
rol rand3
rol rand4
rts

RandomByte
ldx #8
RandomByte1
jsr RandomBit
dex
bne RandomByte1
lda rand1
rts

--
Archives available at http://www.biglist.com/lists/stella/archives/
E-mail UNSUBSCRIBE in the body to stella-request@xxxxxxxxxxx to be removed.

```