An easy to use random number generator
Last updated on February 21, 2012, 21:53 by Sebastian Mihai
Here's a simple way to generate random numbers, if you are not getting this functionality from a library already. I've found this sort of function useful for C code on various classic video game consoles:

unsigned int NextRandom = 1337;

unsigned int random() {
  NextRandom = ((NextRandom * 14577) % 190) + 25;
  return NextRandom;
}

In order to add a bit of chaos to this deterministic function, keep calling the function while waiting for user input, or whenever user input is received. By doing this, you are advancing through the sequence generated by random() a different amount for different users, which can translate to wildly varying outcomes in your game - a.k.a. randomness.

For example, you could implement waiting for the Start button to be pressed to begin the game like such:

// wait for Start to be pressed
while( !START_PRESSED ) {
  random();
}

The while loop will likely be executed many times a second, creating very different outcomes for sligh differences in how long each player waits until they press Start.
Also, during your main game loop you can check user input as such:

if( KEYPAD_LEFT_PRESSED ) {
  random();
  //handle left being pressed
  //...
} else if( KEYPAD_RIGHT_PRESSED ) {
  random();
  //handle right being pressed
  //...
}

Again, some players move around more in your game, so that will affect how far we advance through the pseudo-random sequence.
If you use the materials on this page, or any other page on this web site, you do so at your own risk. They are provided "as is". No warranty is provided or implied. I neither guarantee that the materials will work, nor that they will not be harmful in any way.

Keep your computer clean with VMware

MSSQL tips for production databases

Basic Linux tricks

Entropy in code

Trivialization of history through technology

How indexes work

How to use multiple versions of Firefox on the same computer

(My) Useful settings for fresh Windows installations on new computers

Puppy Linux on a computer without a hard drive (on a USB stick!)

An easy to use random number generator

Simple two-column, three-panel web site template