Skip to content

Random Activity: Dice

Level Beginner
Board V1 & V2
Parts micro:bit

What you'll build

Turn your micro:bit into a dice: shake it and it shows a random number from 1 to 6.

Code

7 random-lib1.py
'''
Example: Dice with random library example using micro:bit
By: Meqdad Darwish
'''
from microbit import *
import random

while True:
    if accelerometer.was_gesture('shake'):
        display.scroll('..')
        sleep(500)
        display.show(random.randint(1, 6))

How it works

  • accelerometer.was_gesture('shake') is True if the board was shaken since the last check.
  • random.randint(1, 6) picks a whole number between 1 and 6, inclusive.

Try this next

  • Show dice dot patterns as DIY images instead of digits.
  • Roll two dice and show the total.
  • Use button A for a coin flip with random.choice(['H', 'T']).