pokecrystal-board/home/random.asm

85 lines
1.3 KiB
NASM
Raw Normal View History

Random:: ; 2f8c
2013-09-07 23:47:52 -07:00
; A simple hardware-based random number generator (RNG).
; Two random numbers are generated by adding and subtracting
; the divider to the respective values every time it's called.
; The divider is a register that increments at a rate of 16384Hz.
; For comparison, the Game Boy operates at a clock speed of 4.2MHz.
; Additionally, an equivalent function is executed in VBlank.
; This leaves a with the value in hRandomSub.
push bc
ld a, [rDIV]
ld b, a
ld a, [hRandomAdd]
adc b
ld [hRandomAdd], a
ld a, [rDIV]
ld b, a
ld a, [hRandomSub]
sbc b
ld [hRandomSub], a
pop bc
ret
; 2f9f
BattleRandom:: ; 2f9f
2013-09-07 23:47:52 -07:00
; _BattleRandom lives in another bank.
; It handles all RNG calls in the battle engine, allowing
; link battles to remain in sync using a shared PRNG.
ld a, [hROMBank]
push af
ld a, BANK(_BattleRandom)
rst Bankswitch
call _BattleRandom
2015-02-10 15:14:41 -08:00
ld [PredefTemp + 1], a
2013-09-07 23:47:52 -07:00
pop af
rst Bankswitch
2015-02-10 15:14:41 -08:00
ld a, [PredefTemp + 1]
2013-09-07 23:47:52 -07:00
ret
; 2fb1
2014-05-03 18:44:18 -07:00
RandomRange:: ; 2fb1
; Return a random number between 0 and a (non-inclusive).
2013-09-07 23:47:52 -07:00
push bc
ld c, a
2014-05-03 18:44:18 -07:00
; b = $100 % c
2013-09-07 23:47:52 -07:00
xor a
sub c
2014-05-03 18:44:18 -07:00
.mod
2013-09-07 23:47:52 -07:00
sub c
2014-05-03 18:44:18 -07:00
jr nc, .mod
2013-09-07 23:47:52 -07:00
add c
ld b, a
2014-05-03 18:44:18 -07:00
; Get a random number
; from 0 to $ff - b.
2013-09-07 23:47:52 -07:00
push bc
2014-05-03 18:44:18 -07:00
.loop
2013-09-07 23:47:52 -07:00
call Random
ld a, [hRandomAdd]
ld c, a
add b
2014-05-03 18:44:18 -07:00
jr c, .loop
2013-09-07 23:47:52 -07:00
ld a, c
pop bc
2014-05-03 18:44:18 -07:00
2013-09-07 23:47:52 -07:00
call SimpleDivide
2014-05-03 18:44:18 -07:00
2013-09-07 23:47:52 -07:00
pop bc
ret
; 2fcb