Stage 4: Get flappy!

Flappy bird just isn’t flappy bird if the bird doesn’t flap, right?! We’re going to make it so that the bird flaps when you press button A on the micro:bit.

  • Add the highlighted lines to your code:
    # Flappy bird Stage 4: Get flappy!
    # https://blog.withcode.uk/2016/05/flappy-bird-microbit-python-tutorial-for-beginners
    from microbit import *
    
    display.scroll("Get ready...")
    
    y = 50
    speed = 0
    
    # Game loop
    while True:
        display.clear()
        
        # flap if button a was pressed
        if button_a.was_pressed():
            speed = -8
    
        # accelerate down to terminal velocity
        speed += 1
        if speed > 2:
            speed = 2
            
        # move bird, but not off the edge
        y += speed
        if y > 99:
            y = 99
        if y < 0:
            y = 0
            
        # draw bird
        led_y = int(y / 20)
        display.set_pixel(1, led_y, 9)
        
        # wait 20ms
        sleep(20)

    The import part is line 15. button_a.was_pressed()  checks to see if the button has been pressed since the program started, or since last time you called that function. If the button has been pressed it returns True, otherwise it returns False.

    Setting the speed to -8 if button A has been pressed means that the bird will start to rise up into the air. Gravity will decelerate it and then accelerate it downwards. Magic!

  • We’re also going to start keeping track of the score. Add the line score = 0 under the line that sets speed to 0 (under line 8).
Debug it with code

Find and fix the errors

You can now make it so that you display the score if you press button B.

  • See if you can find and fix the errors in the code below so that when you press button B, the score appears. At the moment, the score should always be 0.

Line 21 displays the score – there’s no problems with this line: display.scroll(“Score:” + str(score))  Notice how you need to convert score (which stores an integer) into a string (using the str() function) before you can add it to the string “Score:”.