# Maths (Arithmetic): DORND

## [Acorn Electron version]

```       Name: DORND                                                   [Show more]
Type: Subroutine
Category: Maths (Arithmetic)
Summary: Generate random numbers
Deep dive: Generating random numbers
Fixing ship positions
Context: See this subroutine in context in the source code
References: This subroutine is called as follows:
* Ghy calls DORND
* GVL calls DORND
* LASLI calls DORND
* LL9 (Part 1 of 12) calls DORND
* Main flight loop (Part 8 of 16) calls DORND
* Main flight loop (Part 11 of 16) calls DORND
* Main game loop (Part 2 of 6) calls DORND
* Main game loop (Part 4 of 6) calls DORND
* nWq calls DORND
* OUCH calls DORND
* SFS1 calls DORND
* STARS1 calls DORND
* STARS2 calls DORND
* STARS6 calls DORND
* TACTICS (Part 1 of 7) calls DORND
* TACTICS (Part 2 of 7) calls DORND
* TACTICS (Part 4 of 7) calls DORND
* TACTICS (Part 5 of 7) calls DORND
* TACTICS (Part 7 of 7) calls DORND
* Ze calls DORND
* DOEXP calls via DORND2

Set A and X to random numbers (though note that X is set to the random number
that was returned in A the last time DORND was called).

The C and V flags are also set randomly.

If we want to generate a repeatable sequence of random numbers, when
generating explosion clouds, for example, then we call DORND2 to ensure that
the value of the C flag on entry doesn't affect the outcome, as otherwise we
might not get the same sequence of numbers if the C flag changes.

Other entry points:

DORND2               Make sure the C flag doesn't affect the outcome

.DORND2

CLC                    \ Clear the C flag so the value of the C flag on entry
\ doesn't affect the outcome

.DORND

LDA RAND               \ Calculate the next two values f2 and f3 in the feeder
ROL A                  \ sequence:
TAX                    \
ADC RAND+2             \   * f2 = (f1 << 1) mod 256 + C flag on entry
STA RAND               \   * f3 = f0 + f2 + (1 if bit 7 of f1 is set)
STX RAND+2             \   * C flag is set according to the f3 calculation

LDA RAND+1             \ Calculate the next value m2 in the main sequence:
TAX                    \
ADC RAND+3             \   * A = m2 = m0 + m1 + C flag from feeder calculation
STA RAND+1             \   * X = m1
STX RAND+3             \   * C and V flags set according to the m2 calculation

RTS                    \ Return from the subroutine
```