So here's our first program - an electronic die. OK, so technically this is the second program - we went from the ultra-simplicity of "Hello, World" straight to here. The program's operation is pretty simple - every time you shake the micro:bit you get a new random number displayed on the screen in the image of a traditional six side die. We found that the shake gesture was pretty hit-and-miss so we made it that you can also press the A button to roll. We expected the gesture recognition to be better, so maybe we're doing it wrong? Suggestions welcome!
The code is commented and hopefully it's pretty self explanatory. The basic overview is that we define six images, each one looking like the a face of a die. We then randomly display one of these images whenever we shake the micro:bit or press the A button. We added a couple of delays to a make the whole thing feel nicer - first of all we clear the display and leave a short delay after the shake/button to give the user a simple bit of feedback so that they know that they've activated the roll, the second delay is after the new roll has been displayed so that the user doesn't accidentally re-trigger another roll immediately. Finally, we added a couple of lines of code to clear the inputs. This might not seem important, but try taking it out and see what happens. Hint: notice what happens if you quickly double press the A button.
Here's the code:
And here is the code as a text file (with Python's ".py" extension) and a ".hex" file. You can load the .py file into the micro:bit code editor, and you can flash the .hex file directly onto your micro:bit by dragging and dropping like you would with any other .hex file