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:
Flap!Python12345678910111213141517181920212223242526272829303132333435# Flappy bird Stage 4: Get flappy!# http://blog.withcode.uk/2016/05/flappy-bird-microbit-python-tutorial-for-beginnersfrom microbit import *display.scroll("Get ready...")y = 50speed = 0# Game loopwhile True:display.clear()# flap if button a was pressedif button_a.was_pressed():# accelerate down to terminal velocityspeed += 1if speed > 2:speed = 2# move bird, but not off the edgey += speedif y > 99:y = 99if y < 0:y = 0# draw birdled_y = int(y / 20)display.set_pixel(1, led_y, 9)# wait 20mssleep(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).
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:”.
Previous page Next page