I am working on a university project in assembly nasm. The only problem is i am not able to generate an even random number between 162 and 278. I have tried many algorithms but cant seem to restrict the number in range.
Is there a small trick or tweak to get the desired number in range? The aim is to display a fruit randomly on the screen(It is mainly a snake game).
generate an even random number between 162 and 278
"generate random number"
The task of displaying a fruit in a snake game is not too demanding, so I think using the TimeStampCounter is quite ok. You'll continu with the low dword found in EAX.
-
rdtsc ; -> EDX:EAX
"number between 162 and 278"
To restrict the number to your desired range of [162,278], you calculate
(RandomNumber mod NumbersInTheRange) + StartOfTheRange.
EAX register from the 1st step. upper bound - lower bound + 1. Don't forget that +1. -
xor edx, edx ; Required because there's no division of EAX solely
mov ecx, 278 - 162 + 1 ; 117 possible values
div ecx ; EDX:EAX / ECX --> EAX quotient, EDX remainder
mov eax, edx ; -> EAX = [0,116]
add eax, 162 ; -> EAX = [162,278]
"even number"
Make the number even by dropping its lowest bit.
-
and eax, -2 ; -> EAX = {162,164,...,276,278}
I look a little bit in this post: nasm random number generator function. Maybe you can try (rdtsc % (278 - 162) / 2 + 162 / 2) * 2. I hope I helped you :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With