Stage 5: Show those pipes
So far, all we’ve got is a bird that flaps up and falls down. Not much of a game. As soon as we add a pipe that we’ve got to dodge, it starts to get much more fun.
The pipes will eventually scroll across the screen from right to left. They’re going to have a gap of 2 LEDs for the bird to try to squeeze between. We want them to appear in a random position so that sometimes you’ve got to flap to the top of the screen, sometimes to the bottom and sometimes in the middle.
- Add the line
import random near the top, under the line that says
from microbit import *
This imports the random module, which lets us choose a random number. We need a random number so that the pipes don’t always show in the same place.
- Above the line that starts the
while True: loop, add in the following lines:
Python12131415161718192021# Make an image that represents a pipe to dodgedef make_pipe():i = Image("00003:00003:00003:00003:00003")gap = random.randint(0,3) # random wall positioni.set_pixel(4, gap, 0) # blast a hole in the pipei.set_pixel(4, gap+1, 0)return i# create first pipei = make_pipe()
Lines 13 to 18 define a new function called make_pipe . Line 21 uses this function to create a new image of a pipe called i .
i = Image("00003:00003:00003:00003:00003") creates a new image for a micro:bit called i . This is a local variable which means it only exists in the function it’s defined in. That’s a confusing way of saying that we can’t access, use or change this local variable called i anywhere other than inside make_pipe (lines 14-18).
The numbers represent the brightness of the LEDS and the colons (:) represent a new line. So this image is a dim line from top to bottom on the far right of the screen.
Line 15 chooses a random position for a hole in this line: gap = random.randint(0,3) and lines 16 and 17 replace the pixels at that position and the pixel below it with zero brightness to turn the LEDs off.
- Next, we need to display the pipe image. We’ll do this instead of clearing the display. Find the line that said
display.clear() and replace it with
We don’t need to clear the display any more, because our image of a pipe not only tells the micro:bit to display the pipe but also to switch off all of the other LEDs. We could keep display.clear() and put display.show(i) underneath but when coding games you always try to make your code run as efficiently as possible by removing anything that takes up unnecessary processing time and resources.
We’re almost there now. Try out the code we’ve got so far below and make a list of the things that you think we still need to do to finish our game:
Previous page Next page