rand: Replaced rand with a very basic feedback shift register
authorLukas Krickl <lukas@krickl.dev>
Sat, 15 Feb 2025 14:17:18 +0000 (15:17 +0100)
committerLukas Krickl <lukas@krickl.dev>
Sat, 15 Feb 2025 14:17:18 +0000 (15:17 +0100)
This is by no means perfect but it is more random than what was here
before

src/rand.s
src/wram.s

index f0a22db1b9637c0b715601636b41681ac5a675d7..fc6007b8202f5135abde16a32a377bff1520e540 100644 (file)
@@ -2,9 +2,14 @@
 rand_init:
   call mbc1_ram_enable
 
+  ; restore seed from 
+  ; sram 
   ld a, [sram_srand] 
   ld [srand], a
 
+  ld a, [sram_srand+1]
+  ld [srand+1], a
+
   call mbc1_ram_disable
   ret
 
@@ -12,65 +17,59 @@ rand_init:
 rand_save_srand:
   call mbc1_ram_enable
   
+  ; save seed in sram
   ld a, [srand]
   ld [sram_srand], a
 
+  ld a, [srand+1]
+  ld [sram_srand+1], a
+
   call mbc1_ram_disable
   ret
 
   ; gets a pseudo-random number
   ; and advances to the next seed
+  ; using xorshift LFSR 
   ; uses:
   ;   a, hl, de
   ; returns:
   ;   a: random value
 rand:
+  ; load seed
   ld a, [srand]
-  cp a, (rand_table_end - rand_table)
-  jr nz, @not_end REL
-    ld a, 0
-@not_end:
-  ld d, 0
-  ld e, a ; de = offset into table 
+  ld h, a
+  ld a, [srand+1]
+  ld l, a
+
+
+  ; perform lfsr 
+  ; TODO: this can be made much better
 
-  ld hl, rand_table
-  add hl, de
-  inc a
-  ld [srand], a ; srand++
+  ; h
+  ld a, h
+  rra 
+  ld a, l
+  rra
+  xor a, h
+  swap a
+  ld h, a
 
-  ld a, [hl]
+  ; l 
+  ld a, l
+  rra 
+  ld a, h
+  rra
+  xor a, l
+  swap a
+  ld l, a
+
+  ; store seed back
+  ld a, h
+  ld [srand], a
+  ld a, l
+  ld [srand+1], a
+  
+  ld a, [srand]
 
   ret
 
-rand_table:
-.db 0x09, 0xd7, 0xf4, 0xb1, 0x77, 0x61, 0xdd, 0x0e, 0xee 
-.db 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-.db 0xb4, 0xe5, 0x04, 0x8f, 0x8a, 0xcc, 0xbe, 0xbc, 0x78 
-.db 0x2e, 0x3f, 0x1e, 0x84, 0x4c, 0xf0, 0x7d, 0x28, 0x03 
-.db 0xf1, 0x53, 0x8c, 0x0a, 0xb0, 0x3d, 0x94, 0xc9, 0x4a 
-.db 0x93, 0x45, 0x0b, 0xc8, 0x83, 0x4d, 0xbf, 0x5d, 0x34 
-.db 0xef, 0xd3, 0xfd, 0x98, 0x51, 0x54, 0x66, 0x40, 0xce 
-.db 0xc7, 0x12, 0x80, 0xfc, 0x48, 0xbb, 0x55, 0xec, 0x00 
-.db 0xc2, 0x13, 0x39, 0x87, 0xc4, 0x0c, 0xc0, 0xad, 0x1d 
-.db 0x63, 0x23, 0xac, 0x5c, 0x8e, 0xed, 0xb3, 0x85, 0x08 
-.db 0x73, 0x70, 0x62
-rand_table_end:
index 1ec0924f3a114f5db90ee9cde6c5e45ac27ef4ed..4cad0a29f9a673c076f50c0bfb5d3980cf590403 100644 (file)
@@ -75,7 +75,9 @@ game_over_timer: .adv 1
 
 game_mode: .adv 1
 
-srand: .adv 1
+  ; 16 bit srand seed
+  ; seed must never be 0
+srand: .adv 2
 
   ; who is currently in control of the game
   ; if set to FF