2.6 Randomness
Random Numbers in Greenfoot
Unit 2: Variables, Decisions, and Input · Lesson 2.6 · about 25 minutes · no coding experience needed
A game where the enemy always does the same thing stops being interesting on the second play. Randomness is one method call, and one off-by-one that catches nearly everybody.
What you will be able to do
- Use Greenfoot.getRandomNumber and state its exact range
- Shift a random range to start somewhere other than zero
- Make an event happen a set percentage of the time
Words you will need
- Exclusive upper bound
- In plain words The number you pass in is never one of the answers.
- More precisely getRandomNumber(n) returns a value in 0 to n-1 inclusive.
Build it step by step
Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.
-
Step 1
On your screen A Greenfoot method result dialog showing a random number produced by getRandomNumber.
int n = Greenfoot.getRandomNumber(6);This gives a whole number from 0 to 5.
NOT 1 to 6. NOT 0 to 6. The number you pass in is the count of possible answers, and it is never itself one of them.
Six possible values, starting at zero. Say "six possibilities" rather than "up to six" and you will get it right every time.
-
Step 2
On your screen A dice roll produced by shifting a random number up by one.
int dice = Greenfoot.getRandomNumber(6) + 1; // 1 to 6To roll a real dice you want 1 to 6, so take the 0-to-5 and shift the whole range up by one.
The pattern for any range: `getRandomNumber(howMany) + lowest`. For 5 to 10 that is six possible values starting at 5, so `getRandomNumber(6) + 5`.
-
Step 3
On your screen An actor spawning at a random horizontal position along the top of the world.
int x = Greenfoot.getRandomNumber(getWidth()); addObject(new Coin(), x, 0);A random position across the world. Because the upper bound is exclusive this is exactly right: valid x values run from 0 to getWidth() - 1, and that is precisely what this produces.
If the bound had been inclusive, this line would occasionally place a coin one cell outside the world. The exclusive rule is doing you a favor here.
-
Step 4
On your screen A rare event triggered by comparing a random number to a small threshold.
if (Greenfoot.getRandomNumber(100) < 5) { addObject(new Enemy(), 0, 0); }A 5 percent chance, checked every frame.
The numbers 0, 1, 2, 3 and 4 are below 5, and there are 100 possibilities, so it fires about five times in a hundred.
Remember act() runs many times a second. Five percent per FRAME is not rare at all; it is several enemies a second. Percentages here are per frame, not per game.
Mistakes almost everyone makes here
These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.
Common wrong idea getRandomNumber(6) gives 1 to 6.
What is actually true It gives 0 to 5.
Why it matters Every dice, every menu choice, every random lane is off by one if you believe this.
Common wrong idea getRandomNumber(6) can return 6.
What is actually true The upper bound is exclusive and is never produced.
Why it matters Believing otherwise leads to array errors in Unit 5, where the last valid index is always one less than the length.
Common wrong idea A 5 percent chance in act() is rare.
What is actually true act() runs many times a second, so it happens several times a second.
Why it matters This is why beginners drown their scenario in enemies and think spawning is broken.
Common wrong idea Random means every value appears the same number of times.
What is actually true Each value is equally LIKELY. Short runs can look very lopsided.
Why it matters Students often "fix" working random code because five heads in a row looked wrong.
Check your understanding
Answer these before moving on. They are graded instantly and you can retry.
-
1. What are the possible values of `Greenfoot.getRandomNumber(4)`?
-
2. Which expression gives a number from 1 to 10?
-
3. Which expression gives a number from 5 to 10?
-
4. Roughly how often does `if (Greenfoot.getRandomNumber(10) < 1)` fire?
Fill in the code
Spawn a coin at a random height down the left edge of the world, and only about one frame in fifty. Remember which bound is exclusive.
if (Greenfoot.getRandomNumber() < 1)
{
int y = Greenfoot.getRandomNumber();
addObject(new Coin(), 0, y);
}
Stuck? Open a hint for each blank
- Blank 1: One chance in how many?
- Blank 2: A method on the world that reports how tall it is. Do not forget the parentheses.
Lesson quiz
This one counts toward your progress. Take it when the section above makes sense.
-
1. getRandomNumber(1) always returns:
-
2. You want a random lane from 0 to 4. Which call?
-
3. Why is an exclusive upper bound convenient with getWidth()?
-
4. A student says their 2 percent spawn chance is "spawning constantly". What is the most likely explanation?
The short version
- getRandomNumber(n) gives 0 to n-1. The n itself never appears.
- To shift a range: getRandomNumber(howMany) + lowest.
- A percentage checked in act() is per FRAME, not per game.
- Equally likely is not the same as evenly spread.
If you get stuck
These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]