Lesson 18: Electronic dice
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Roll without a dice
- A board game needs a dice, but you lost it. The Arduino can be one.
- Six LEDs show the number: 1 LED for a one, all 6 for a six.
- A button rolls, and
randompicks the number, so nobody knows what comes next.
Words for this lesson
| Word | Meaning |
|---|---|
| dice | a small cube with the numbers 1 to 6 for games |
| roll | throw the dice to get a number |
| random | you cannot say before what it will be |
| function | a named block of code you can use many times, like show(n) |
English
Which LEDs are on?
| n | Pins on | Pins off |
|---|---|---|
| 1 | 2 | 3, 4, 5, 6, 7 |
| 3 | 2, 3, 4 | 5, 6, 7 |
| 6 | 2, 3, 4, 5, 6, 7 | none |
- LED number i (counting from 0) is on pin 2 + i. So the first
nLEDs are pins 2 to 1 + n.
English
A random number
void setup() {
Serial.begin(9600);
for (int i = 0; i < 5; i++) {
Serial.println(random(1, 7));
}
}
void loop() {
}
random(1, 7)gives 1, 2, 3, 4, 5 or 6. The 7 is the first number it never gives.- On a real board the numbers come in the same order after every reset.
randomSeed(analogRead(A0));insetupmixes them up, because a pin with nothing on it reads a slightly different value each time.
English
In the exam
In IGCSE pseudocode (0478), RANDOM() gives a random number from 0 to 1, with decimals. To get a whole number in a range, multiply, round and add.
| 0478 pseudocode | Gives |
|---|---|
ROUND(RANDOM() * 5, 0) + 1 |
1 to 6, like random(1, 7) |
ROUND(RANDOM() * 19, 0) + 1 |
1 to 20, like random(1, 21) |
- 0478/23/M/J/23 Q2: explain the purpose of the library routine RANDOM: it gives a (pseudo) random number, usually in a range you choose.
- 0478/21/M/J/24 Q4:
Limit ← ROUND(RANDOM() * 19, 0) + 1picks a whole number from 1 to 20. - 0478/21/M/J/25 Q6(a): find the errors in a guessing game. One is line 02:
ROUND(RANDOM() * 99, 1) + 1rounds to 1 decimal place, so N is not a whole number. The correction isROUND(RANDOM() * 99, 0) + 1.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Six LEDs on pins 2 to 7 show a number: 3 means the first three LEDs are on. Finish the function show(n): first switch all six off, then switch on the first n. The loop already counts 1, 2, 3, 4, 5, 6 with half a second for each number.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Now roll the dice. The button on pin 8 starts a roll: random(1, 7) gives a number from 1 to 6. Show it with show, and print You rolled: and the number. Before the first press all LEDs are off.
点击“运行”查看此处输出。