summaryrefslogtreecommitdiff
path: root/home/random.asm
diff options
context:
space:
mode:
authorehw <Knuckles500@gmail.com>2018-06-05 11:03:34 -0400
committerGitHub <noreply@github.com>2018-06-05 11:03:34 -0400
commita62cf40b29a814188c545e47d7534b6ea3aebcc1 (patch)
tree3db618e96e50af65d6831e4ce2540fb0435a954e /home/random.asm
parent771d125c7564a0ff1e511733114d53ad0521c3f8 (diff)
parentc4c2b3cc6ede5259a1246c195a8c1d58e6d3a35d (diff)
Merge pull request #4 from pret/master
Merge master
Diffstat (limited to 'home/random.asm')
-rw-r--r--home/random.asm69
1 files changed, 69 insertions, 0 deletions
diff --git a/home/random.asm b/home/random.asm
new file mode 100644
index 0000000..5ca7c78
--- /dev/null
+++ b/home/random.asm
@@ -0,0 +1,69 @@
+include "constants.asm"
+
+if DEBUG
+SECTION "Random Number Generation", ROM0 [$3270]
+else
+SECTION "Random Number Generation", ROM0 [$3234]
+endc
+
+Random::
+; 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.
+
+; This implementation also takes the current scanline as read from rLY
+; and adds it nybble-swapped to the value of the divider. The unswapped
+; value of rLY is also added to the value that's subtracted.
+
+; Additionally, an equivalent function is executed in VBlank.
+
+; This leaves a with the value in hRandomSub.
+
+ push bc
+
+ ldh a, [rLY]
+ ld c, a
+ swap a
+ ld b, a
+ ldh a, [rDIV]
+ adc b
+ ld b, a
+ ldh a, [hRandomAdd]
+ adc b
+ ldh [hRandomAdd], a
+
+ ldh a, [rLY]
+ swap a
+ ld b, a
+ ldh a, [rDIV]
+ adc b
+ adc c
+ ld b, a
+ ldh a, [hRandomSub]
+ sbc b
+ ldh [hRandomSub], a
+
+ pop bc
+ ret
+
+BattleRandom::
+; _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]
+ push af
+ ld a, BANK(_BattleRandom)
+ call Bankswitch
+
+ call _BattleRandom
+
+ ld [wPredefHL + 1], a
+ pop af
+ call Bankswitch
+ ld a, [wPredefHL + 1]
+ ret