In this tutorial we'll take advantage of the 'shake' accelerometer gesture to build a dice shaker, which can be used to play all kinds of games.
from microbit import *
import random
while True:
if accelerometer.was_gesture('shake'):
# generate a random integer from 1 to 6
diceNumber = random.randint(1,6)
# show the dice number
display.show(str(diceNumber))
sleep(1000)
Notice here we import the random MicroPython library module as well as the standard microbit library module.
After you've downloaded this program to the micro:bit try to shake a six!
As a extra coding challenge you could modify the code to simulate two dice (hint: the minimum throw is 2 and the maximum is 12).
Return to the micro:bit MicroPython Coding Tutorials page.
No comments:
Post a Comment