Basic Random Number for Games

Random number is one of the most fundamental and important elements in video game programming. It’s being used in many different aspects such as AI (artificial intelligence), procedural content generation, unit stat, and so on which makes your game less predictable and thus increases the level of replayability of your game.

I first learned to use random numbers in one of my earliest game projects (circa 2006), a simple scissors-paper-stone game made in Macromedia Flash 8 (now known as Adobe Flash):

Random numbers were used for its AI, which basically a set of numbers ranging from 0 to 2, like so:

A random number will be generated at the beginning of each round to determine the AI’s selection and then an animation will be played according to the result. Winning or losing for each round will be determined by comparing the number generated by the AI with the number selected by player.

For example:

Player AI Result
0 (scissors) 1 (paper) Player wins
2 (stone) 0 (scissors) Player wins
1 (paper) 2 (stone) AI wins

This simple logic can be used in most games with minor iterations. Below I have included code snippets for random number generation in several different scripting languages so that you can copy and paste refer to it when needed. All it does is generates a pseudo random number between 0 to 2 with time seed. Happy coding!



int main()
    srand((unsigned)time(0)); //srand() only needs to call once
    int result;
    result = rand()%3; //this will generate a number between 0 to 2
   return 0;

Unity script:

var result : int = Random.Range(0, 2);

Action script:

function randRange(min:Number, max:Number):Number
    var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomNum;
var result:Number = randRange(0, 2);


random.randint(1, 2)

Lastly, please allow me to share with you a comic about random numbers, illustrated by Scott Adams.