What you learn today
- Random values between 0 and 1
- Scale ranges
- Light effects
In the emergency corridor a light should flicker like a loose contact, and above the bar an LED display changes colour. With fixed values or a counter it looks like clockwork – after three seconds everyone sees the pattern. What is missing is randomness.
rand: a number between 0 and 1
rand z # 0 <= z < 1, new every time
rand writes a new random number into the register on every call. It is at least 0 and always less than 1 – exactly 1 never comes out. If you need the same random value twice, call rand once and then use the register. A second call returns a different number.
Scaling ranges
You turn 0 to 1 into any range with mul (width) and add (start):
| Goal | Calculation |
|---|---|
| 0 to below 10 | mul z z 10 |
| 20 to below 30 | mul z z 10, then add z z 20 |
| whole number 0 to n − 1 | mul z z n, then floor z z |
| die 1 to 6 | mul z z 6, floor z z, add z z 1 |
| “yes” in 30 % of cases | slt yes z 0.3 |
The last line is often the most useful one: slt compares the random number with a probability and returns 1 in about 30 out of 100 cases.
Light effects
A light only knows On. So flickering means: every tick you roll again whether it is lit.
rand z
slt lit z CHANCE # CHANCE = 0.8: on with 80 %
sbn LIGHT HASH("Gang") On lit
An LED display can change its colour as well. The twelve colours from Color.Blue (0) to Color.Purple (11) are simply numbers:
rand z
mul colour z COLOURS # COLOURS = 12
floor colour colour # 0 to 11
sbn DISPLAY HASH("Bar") Color colour
Use floor for whole random numbers, not round. round turns 0 to below 12 into thirteen possible values: there is no colour 12 at all, and 0 and 12 only come up half as often as all the others.
Rolling every tick gives up to two changes per second – fine for flickering, too hectic for a calm mood. Roll a waiting time instead, say 2 to 8 ticks, and count it down before the light switches again.
Exercise
Task
A lever “Party” switches the LED display “Bar” into party mode.
- Lever on (
Open= 1): every tick a random colour from 0 to 11 onColorand a die roll from 1 to 6 onSetting - Lever off: colour
Color.White,Setting0 - If the lever is missing, “off” applies
The lever is already read and the output is already there. The two random values are missing. round is not allowed here.
Hints
Hint 1
Random colour: rand z, mul colour z COLOURS, floor colour colour.
Hint 2
Die: a second rand z, times SIDES, floor, then add num num 1.
Hint 3
The select lines at the end already choose between random and fixed values.
Quiz
5 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in