-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.s
More file actions
96 lines (85 loc) · 1.67 KB
/
random.s
File metadata and controls
96 lines (85 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
; prng
;
; Returns a random 8-bit number in A (0-255), clobbers X (0).
;
; Requires a 2-byte value on the zero page called "seed".
; Initialize seed to any value except 0 before the first call to prng.
; (A seed value of 0 will cause prng to always return 0.)
;
; This is a 16-bit Galois linear feedback shift register with polynomial $002D.
; The sequence of numbers it generates will repeat after 65535 calls.
;
; Execution time is an average of 125 cycles (excluding jsr and rts)
.include "global.inc"
.segment "ZEROPAGE"
seed: .res 2 ; initialize 16-bit seed to any value except 0
.segment "CODE"
; clobbers: x and accum
prng:
ldx #8 ; iteration count (generates 8 bits)
lda seed+0
:
asl ; shift the register
rol seed+1
bcc :+
eor #$2D ; apply XOR feedback whenever a 1 bit is shifted out
:
dex
bne :--
sta seed+0
cmp #0 ; reload flags
rts
; generate random value from 1-2
d2:
jsr prng
and #%00000001
beq d2_eq
lda #$01
rts
d2_eq:
lda #$02
rts
; generate random value from 1-3
d3:
jsr prng
; divide result by 3
ldx #3
jsr divide
; add 1 to remainder get 1-3
clc
adc #1
rts
; generate random value from 1-4
d4:
jsr prng
and #%00000011
clc
adc #$01
rts
; generate random value from 1-6
d6:
jsr prng
; divide result by 6
ldx #6
jsr divide
; add 1 to remainder get 1-6
clc
adc #1
rts
; generate random value from 1-8
d8:
jsr prng
and #%00000111
clc
adc #$01
rts
; generate random value from 1-12
d12:
jsr prng
; divide result by 12
ldx #12
jsr divide
; add 1 to remainder get 1-12
clc
adc #1
rts