Quantcast
Channel: x86 Assembly - Programmers Heaven
Viewing all articles
Browse latest Browse all 152

Random number generator causing divide overflows

$
0
0
I've been working on a 16-bit real-mode game for several months now, and I've had a custom random number generator written and tested for a good portion of that. It uses DOS interrupt 21h function 2Ch to return the system time as a seed for some arbitrary math operations, and the random 16-bit number is returned in AX, like so:
[code] public Random
Random proc
push bx
push cx
push dx
call GetSystemTime
push cx
mov cl,8
shr dx,cl ;Move DH into DL
pop cx
mov dh,cl ;Move minutes from CL to DH
mov ax,dx ;Save to AX
mov cl,13h
rcr ax,cl ;Rotate right to monkey with bits.
mov bx,7
mul bx ;Multiply by 13h to monkey further.
pop dx
pop cx
pop bx
ret
Random endp

public GetSystemTime
GetSystemTime proc
push ax
mov ah,2Ch
int 21h
pop ax
ret
GetSystemTime endp
[/code]
I then use division to limit the range to only what I need, like pulling a random monster from a data table or rolling for attack, defense, and damage.

The problem is that when I use ranges of less than 10 I periodically get a divide overflow, with smaller ranges causing more of them. I'm using an 8-bit value in BL, but BH and DX are zeroed out so I can divide DX:AX by BX and leave the remainder in DX where it's a little more convenient.

Any ideas on how I can improve my RNG or better limit the range of numbers?

Viewing all articles
Browse latest Browse all 152

Trending Articles