Search code examples
pythonbbc-microbit

What is wrong with my code in python?


In my code, its supposed to be a magic 8 ball that is rigged. Pressing A should show "Yes!", pressing B should show "No." But every time, it shows "Yes!" without any buttons being pressed.

from microbit import *
import random

frameq = Image("00000:""00000:""00900:""00000:""00000")
framew = Image("00000:""09990:""09390:""09990:""00000")
framee = Image("99999:""93339:""93339:""93339:""99999")
framer = Image("33333:""33333:""33333:""33333:""33333")
framet = Image("22222:""22222:""22222:""22222:""22222")
framey = Image("11111:""11111:""11111:""11111:""11111")
frames = [frameq, framew, framee, framer, framet, framey]
answers = [
    "It is certain",
    "It is decidedly so",
    "Without a doubt",
    "Yes, definitely",
    "You may rely on it",
    "As I see it, yes",
    "Most likely",
    "Outlook good",
    "Yes",
    "Signs point to yes",
    "Reply hazy try again",
    "Ask again later",
    "Better not tell you now",
    "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",
]
apress = False
bpress = False
while True:
    if button_a.is_pressed:
        bpress = False
        apress = True
    elif button_b.is_pressed:
        apress = False
        bpress = True
    display.show("8")
        if accelerometer.was_gesture("shake") and apress is True:
        display.clear()
        display.show(frames, loop=False, delay=250)
        sleep(1000)
        display.show("Yes!")
        apress = False
    elif accelerometer.was_gesture("shake") and bpress is True:
        display.clear()
        display.show(frames, loop=False, delay=250)
        sleep(1000)
        display.show("No.")
        bpress = False
    elif accelerometer.was_gesture("shake"):
        display.clear()
        display.show(frames, loop=False, delay=250)
        sleep(1000)
        display.scroll(random.choice(answers))

It shows no error message, it just shows "Yes!" every single time I shake. And by the way, "Yes!" is not in the answers array, only "Yes", and I always see the !.


Solution

  • Without any more context, one can only assume what the problem is. Make sure that is_pressed is not a function:

    if button_a.is_pressed:
        bpress = False
        apress = True
    elif button_b.is_pressed:
        apress = False
        bpress = True
    

    if is_pressed is a function then button_a.is_pressed will always be True hence apress will always be True hence you will always get 'Yes!' printed.

    Try to change the above code to

    if button_a.is_pressed():
        bpress = False
        apress = True
    elif button_b.is_pressed():
        apress = False
        bpress = True
    

    Otherwise, debug you program. Add print statements in different execution paths and see what causes each if statement to be True.