(CGA) Using Random Lesson

Using Random

Game designers use random techniques so the game will not be the same every time you play. Random allows the program to randomly pick a value from a range of values.

In Greenfoot, the getRandomNumber() method is used to generate random numbers, within a specified range, to create randomly generated behavior.

The method is in the Greenfoot class.

code block and explanation:
static int
getRandomNumber (int limit)
Return a random number between o (inclusive) and limit (exclusive).
getRandomNumber
public static int getRandomNumber (int limit)
Return a random number between o (inclusive) and limit (exclusive).
Parameters:
limit An upper limit which the returned random number will be smaller than.
Returns:
A random number within 0 to (limit-1) range.

It is a static method that returns a random number between zero and a parameter limit -1.

Any method used from the Greenfoot class must be called by the class using dot notation.  

Dot notation format

  1. Name of class or object to which the method belongs
  2. Dot
  3. Name of method to call
  4. Parameter list
  5. Semicolon

Example

Greenfoot.getRandomNumber(30);

The Greenfoot.getRandomNumber(int limit)

This returns a random number between 0 (inclusive) and the limit (exclusive)

Greenfoot.getRandomNumber(30);  

This would produce a number from 0 (inclusive) and 30 (exclusive). In other words, it would produce random numbers in the range of 0 to 29.  

It can be used in various ways.

addObject(bird1, Greenfoot.getRandomNumber(820), Greenfoot.getRandomNumber(600));
Add the object somewhere in the world that is 820width by 600 height.
int count = Greenfoot.getRandomNumber(3);
Store a random number in a variable.
setLocation(getX() + Greenfoot.getRandomNumber(820), getY() + Greenfoot.getRandomNumber(600));
Set the location of an object to a random place in the world
turn(Greenfoot.getRandomNumber(270));
Turn an object a random degree

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION