In this challenge we will code our BBC micro:bit to create a “rolling dice” animation.
Our code will generate random numbers between 1 and 6 to create the animation and will include 8 frames. The last frame will be the number picked up by the dice. Here is a preview of the animation (on an infinite loop):
You can recreate this digital dice using the BBC micro:bit website.
Building the code, step by step:
Our “rolling the dice” animation will start when the user presses the A button on the micro-bit.
To create the animation we will then use a loop (repeat 8 times):
For each frame we will generate a random number between 1 and 6 using the following code:
We will then check the value of this random number using an IF block:
To display this number as it will appear on a dice we will use the “show leds” block:
We will repeat the last two steps for all the 6 possible faces of the dice by adding ELSE IF blocks to our IF block:
Finally we will add a pause between each frame (between each iteration of the loop):
Here is the complete code for our dice: