8-Ball

"""
    8-Ball Message Generator
    Copyright (c) 2016 Multiple Authors
    MIT  Licence
"""

from microbit import *
import random

# list of possible answers
answers = [
    "It is certain",
    "It is decidedly so",
    "Cannot predict now",
    "Concentrate and ask again",
    "Don't count on it",
    "My reply is no",
    "My sources say no",
    "Outlook not so good"
    "Very doubtful",
]

while True:
    display.show("8")
    if accelerometer.was_gesture("shake"):
        display.clear()
        sleep(1000)
        
        # 1 pick a random item from the list. 
        # 2 Convert it to a string
        # 3 scroll it.
        display.scroll(random.choice(answers))

Code Explained

answers List

Each of the possible messages is held in a list. A list holds multiple values. In this example, the list has 9 values and each one of those 9 values is a string (of characters).

answers = [
    "It is certain",
    "It is decidedly so",
    "Cannot predict now",
    "Concentrate and ask again",
    "Don't count on it"
    "My reply is no",
    "My sources say no",
    "Outlook not so good",
    "Very doubtful",

The square brackets and each item is separated by a comma. The list can also be arranged on a single line:

answers = ["It is certain", "Dont count on it", "Ask again",]

Was it Shaken?

if accelerometer.was_gesture("shake") is True:

.was_gesture(gesture) returns a True or False depending on whether gesture was the most recently detected gesture. .was_gesture(freefall) would return True if the microbit was thrown into the air.

The API for the accelerometer module lists other gestures that can be used.

Random Choice from List

display.scroll(answers.choice)

.choice picks a random item from the answers list.

Using random requires the random module to be imported. This is done at the beginning of the program:

from microbit import *
import random

A module (like random) is a collection of pre-existing code you can reuse.

Share On
Facebook Twitter Google Plus

Published: December 23, 2016 Updated: December 23, 2016

8-Ball

Make a funky 8-ball for the microbit. It shows a different message each time it’s shaken.