Forked from JohnConnolly0/ZX Spectrum Random Numbers
Last active
August 18, 2019 16:50
-
-
Save UnQuaiz/6a81b82d065b054148d853caf66de2cf to your computer and use it in GitHub Desktop.
ZX Spectrum Random number generators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LD A,R ; Load the A register with the refresh register | |
LD L,A ; Copy register A into register L | |
AND %00111111 ; This masking prevents the address we are forming from accessing RAM | |
LD H,A ; Copy register A into register H | |
LD A,(HL) ; Load the pseudo-random value into A | |
; HOW THIS WORKS | |
; The refresh register in the Z80 is highly unpredictable since it is incremented every cycle. | |
; Because it may be at any value when this routine is called, it is very good for random numbers. | |
; This routine increases the randomness of the number since it forms an address based on the | |
; refresh counter's current status and accesses the memory at that address. | |
; It can also be modified to get a sixteen-bit pseudo-random number by changing line 5 to LD D,(HL) | |
; and adding these two lines to the end: | |
; INC L | |
; LD E,(HL) | |
; This routine was written for the ZX Spectrum which has a 16KB ROM. If you plan to use this routine | |
; on another Z80 system, change the binary value at the AND instruction. For example, if you had a | |
; Z80 computer with an 8KB ROM, you would change the binary value to %00011111. |
; Random Number Generator (8-bit) Edit
; Generates a psuedo random number between 00h and FFh
; the random number is loaded into A.
; The seed for the random number is held at location RandSeed.
ld hl,(RandSeed)
ld a,r
ld d,a
ld e,(hl)
add hl,de
add a,l
xor h
ld (RandSeed),hl
; Simple pseudo-random number generator.
; Steps a pointer through the ROM (held in seed), returning
; the contents of the byte at that location.
random:
ld hl,(seed) ; Pointer
ld a,h
and 31 ; keep it within first 8k of ROM.
ld h,a
ld a,(hl) ; Get "random" number from location.
inc hl ; Increment pointer.
ld (seed),hl
ret
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
; Fast RND
;
; An 8-bit pseudo-random number generator,
; using a similar method to the Spectrum ROM,
; - without the overhead of the Spectrum ROM.
;
; R = random number seed
; an integer in the range [1, 256]
;
; R -> (33*R) mod 257
;
; S = R - 1
; an 8-bit unsigned integer
ld a, (seed)
ld b, a
rrca ; multiply by 32
rrca
rrca
xor 0x1f
add a, b
sbc a, 255 ; carry
ld (seed), a
ret