Random Numbers
Random Numbers
Computers follow instructions and will only do what you tell them to do. They will do the same thing every time you ‘run’ the program. This is a good thing.
However, there are times when you do want your program to do something surprising, for example:
- modelling rolling dice
- picking a name out of a group of students
- shuffling a playlist
- making computer games less predictable
To create random events we need to generate a random number.
We use a purple maths block to pick the random number.
Example
The code below mimics a die (a single dice).
A variable has been created called die. When the micro:bit is shaken, the computer picks a random number between 1 and 6. This number is then assigned (put into) the variable 'die'.
The next block shows the number in the variable 'die' on the LEDs.
Shake the micro:bit to roll the die
Making Random Numbers
Watch the video below to see how to make random number and assign it to a variable.
Challenges
2 Dice Simple
Create a program that:
- When you shake the micro:bit shows a random number between 2 and 12
2 Dice Advanced
Create a program that:
- Has 3 variables:
- Die1
- Die2
- Total
- When you press the A button:
- Assigns a random number between 1 and 6 to the variable Die1
- Shows the value stored in Die 1 on the screen.
- When you press the B button:
- Assigns a random number between 1 and 6 to the variable Die2
- Shows the value stored in Die2 on the screen.
- When you press A and B together:
- Adds the values stored in Die1 and Die2 together. The result is assigned to the variable Total.
- Shows the value stored in the variable Total on the screen.
Key Words
Random
Without order. Numbers are picked within a range as if by chance.
Assigning
Putting a piece of data into a variable