View Page Source

Back to Page
Revision 1 (current)
Edited by Sand on 2/13/2023 2:18 AM
!!! Movies

[module:PublicationHistory|publicationId=5061]

!!! Random number generator

The game's random number generator is the
standard C library function {{[https://cplusplus.com/reference/cstdlib/rand/|rand]}}.
The generator is
seeded from the current time,
before the title screen,
in the common {{srand(time(NULL))}} pattern.

In the version of MARIO.EXE that has MD5 8ccc1e67bb7c362fb64db43db3f3589f,
the RNG code starts at byte offset 0x37f6
(0x09f6 after the EXE header):

%%SRC_EMBED asm
srand:
0x09f6  55            push  bp
0x09f7  8bec          mov   bp, sp
0x09f9  8b4606        mov   ax, word [bp+0x6]  ; ax = seed
0x09fc  c706363c0000  mov   word [0x3c36], 0
0x0a02  a3343c        mov   word [0x3c34], ax  ; x = 0x0000:ax
0x0a05  5d            pop   bp
0x0a06  cb            retf

rand:
0x0a07  8b0e363c      mov   cx, word [0x3c36]
0x0a0b  8b1e343c      mov   bx, word [0x3c34]  ; cx:bx = x
0x0a0f  ba5a01        mov   dx, 0x15a
0x0a12  b8354e        mov   ax, 0x4e35         ; dx:ax = 0x015a4e35
0x0a15  e8a6ff        call  mul32              ; dx:ax = cx:bx * dx:ax
0x0a18  050100        add   ax, 1
0x0a1b  83d200        adc   dx, 0              ; dx:ax = dx:ax + 1
0x0a1e  8916363c      mov   word [0x3c36], dx
0x0a22  a3343c        mov   word [0x3c34], ax  ; x = dx:ax
0x0a25  a1363c        mov   ax, word [0x3c36]
0x0a28  99            cdq                      ; dx:ax = dx:ax >> 16
0x0a29  25ff7f        and   ax, 0x7fff         ; ax = ax & 0x7fff
0x0a2c  cb            retf
%%END_EMBED

The compiled code corresponds to C code like the below.
It is a 32-bit
[https://en.wikipedia.org/wiki/Linear_congruential_generator|linear congruential generator],
but only 15 bits of the state variable
are returned in each call to {{rand}}.

%%SRC_EMBED c
static int x = 1;

void srand(unsigned int seed)
{
	x = seed;
}

int rand(void)
{
	x = x * 22695477 + 1;
	return (x >> 16) & 0x7fff;
}
%%END_EMBED

The executable is compiled with Borland C++, likely version 2.0.
The string {{Borland C++ - Copyright 1991 Borland Intl.}} appears in the file.