gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Coding > generating random numbers

#176975 - blessingta@hotmail.co.uk - Sun Nov 13, 2011 10:11 pm

hi

Are there pre-made functions for generating random numbers?


And whats the equivalent for itoa (INT to CHAR*) conversion? I need this to convert the player's int score for displaying on screen.

#176979 - Dwedit - Mon Nov 14, 2011 12:25 am

There's always stdlib's rand() if you don't care about the quality of your random numbers. People seem to like the mersenne twister algorithm better.
But either way, you need a good source of randomness, otherwise you end up with NDS Deal or No Deal, which always put the top prize in the exact same briefcase every first game.
The easiest way to get good enough randomness is to call your random function at least once per frame.
There's also another way to get randomness, if you're really hardcore about random numbers: measure exactly how long the player pushed the A or Start button at the beginning of the game. To do that, replace the "vblank wait" function with one that:
* Calls the random number function
* Checks the scanline number to see if we hit vblank
* Checks if you are still holding the A/Start button.
* Repeats until vblank is reached, or you released A/Start.
Only use this special version of the vblank wait function at the beginning, when you're waiting for the player to let go of the A button. at the title screen.

For integer to text conversion, try "sniprintf". Traditionally, there's sprintf() for outputting to a string, but that doesn't take into account how big your destination buffer is, so you use snprintf() instead. "sniprintf" makes it integer-only, so it excludes the floating-point conversion code.
_________________
"We are merely sprites that dance at the beck and call of our button pressing overlord."

#176983 - blessingta@hotmail.co.uk - Tue Nov 15, 2011 4:48 pm

thanks I think I'll go with the mersenne twister, but I've been googling for it yet I still can't find an easy implementation of it.

But at the same time how slow is the stdlib's rand() function? this may be hard to justify since I have to use asm within my coursework hence wasting memory will generally be looked down upon.