pokecrystal/home/random.asm

81 lines
1.3 KiB
NASM
Raw Normal View History

2018-06-24 14:09:41 +00:00
Random::
2013-09-08 06:47:52 +00: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-08 06:47:52 +00:00
ld b, a
ldh a, [hRandomAdd]
2013-09-08 06:47:52 +00:00
adc b
ldh [hRandomAdd], a
2013-09-08 06:47:52 +00:00
ldh a, [rDIV]
2013-09-08 06:47:52 +00:00
ld b, a
ldh a, [hRandomSub]
2013-09-08 06:47:52 +00:00
sbc b
ldh [hRandomSub], a
2013-09-08 06:47:52 +00:00
pop bc
ret
2018-06-24 14:09:41 +00:00
BattleRandom::
2013-09-08 06:47:52 +00: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-08 06:47:52 +00:00
push af
ld a, BANK(_BattleRandom)
rst Bankswitch
call _BattleRandom
2018-01-23 22:39:09 +00:00
ld [wPredefTemp + 1], a
2013-09-08 06:47:52 +00:00
pop af
rst Bankswitch
2018-01-23 22:39:09 +00:00
ld a, [wPredefTemp + 1]
2013-09-08 06:47:52 +00:00
ret
2018-06-24 14:09:41 +00:00
RandomRange::
2014-05-04 01:44:18 +00:00
; Return a random number between 0 and a (non-inclusive).
2013-09-08 06:47:52 +00:00
push bc
ld c, a
2014-05-04 01:44:18 +00:00
; b = $100 % c
2013-09-08 06:47:52 +00:00
xor a
sub c
2014-05-04 01:44:18 +00:00
.mod
2013-09-08 06:47:52 +00:00
sub c
2014-05-04 01:44:18 +00:00
jr nc, .mod
2013-09-08 06:47:52 +00:00
add c
ld b, a
2014-05-04 01:44:18 +00:00
; Get a random number
; from 0 to $ff - b.
2013-09-08 06:47:52 +00:00
push bc
2014-05-04 01:44:18 +00:00
.loop
2013-09-08 06:47:52 +00:00
call Random
ldh a, [hRandomAdd]
2013-09-08 06:47:52 +00:00
ld c, a
add b
2014-05-04 01:44:18 +00:00
jr c, .loop
2013-09-08 06:47:52 +00:00
ld a, c
pop bc
2014-05-04 01:44:18 +00:00
2013-09-08 06:47:52 +00:00
call SimpleDivide
2014-05-04 01:44:18 +00:00
2013-09-08 06:47:52 +00:00
pop bc
ret