A dungeon delver roguelike using Pathfinder 2nd edition rules
1SECTION "MathVariables", WRAM0
2
3randstate:: ds 4
4
5SECTION "Math", ROM0
6
7;; From: https://github.com/pinobatch/libbet/blob/master/src/rand.z80#L34-L54
8; Generates a pseudorandom 16-bit integer in BC
9; using the LCG formula from cc65 rand():
10; x[i + 1] = x[i] * 0x01010101 + 0xB3B3B3B3
11; @return A=B=state bits 31-24 (which have the best entropy),
12; C=state bits 23-16, HL trashed
13rand::
14 ; Add 0xB3 then multiply by 0x01010101
15 push hl
16 push af
17 ld hl, randstate+0
18 ld a, [hl]
19 add a, $B3
20 ld [hl+], a
21 adc a, [hl]
22 ld [hl+], a
23 adc a, [hl]
24 ld [hl+], a
25 ld c, a
26 adc a, [hl]
27 ld [hl], a
28 ld b, a
29 pop af
30 pop hl
31 ret
32
33; Sets the random seed to BC.
34; C expects startup code to behave as if srand(1) was called.
35; AHL trashed
36srand::
37 ld hl,randstate+3
38 xor a
39 ld [hl-],a
40 ld [hl-],a
41 ld a,b
42 ld [hl-],a
43 ld [hl],c
44 ret
45
46; HL = D * E
47Multiply::
48 ld hl, 0
49 ld a, d
50 or a
51 ret z
52 ld b, d
53 ld d, h
54.Loop
55 add hl, de
56 dec b
57 jp nz, .Loop
58 ret
59
60; A = A % C
61Modulo::
62.Loop
63 cp c
64 jp c, .Done
65 sub c
66 jp .Loop
67.Done
68 ret