pokecrystal-board/home/random.asm

81 lines
1.3 KiB
NASM
Raw Permalink Normal View History

2018-06-24 07:09:41 -07:00
Random::
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
ldh a, [rDIV]
2013-09-07 23:47:52 -07:00
ld b, a
ldh a, [hRandomAdd]
2013-09-07 23:47:52 -07:00
adc b
ldh [hRandomAdd], a
2013-09-07 23:47:52 -07:00
ldh a, [rDIV]
2013-09-07 23:47:52 -07:00
ld b, a
ldh a, [hRandomSub]
2013-09-07 23:47:52 -07:00
sbc b
ldh [hRandomSub], a
2013-09-07 23:47:52 -07:00
pop bc
ret
2018-06-24 07:09:41 -07:00
BattleRandom::
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.
ldh a, [hROMBank]
2013-09-07 23:47:52 -07:00
push af
ld a, BANK(_BattleRandom)
rst Bankswitch
call _BattleRandom
ld [wPredefHL + 1], a
2013-09-07 23:47:52 -07:00
pop af
rst Bankswitch
ld a, [wPredefHL + 1]
2013-09-07 23:47:52 -07:00
ret
2018-06-24 07:09:41 -07:00
RandomRange::
2014-05-03 18:44:18 -07:00
; 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
ldh a, [hRandomAdd]
2013-09-07 23:47:52 -07:00
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