microbit python tutorial: shake ‘n’ burn fire simulator

In this stage we’re going to randomly set the brightness of the LEDs at the bottom of the fire.

  1. Add the highlighted lines to the bottom of your code:
    from microbit import *
    import random
    
    # create an empty image
    i = Image("00000:"*5)
    
    # start with the fire at medium intensity
    intensity = 0.5
    
    # keep looping
    while True:
        # show the image and wait
        display.show(i)
        sleep(100)
    

    Line 11 while True  makes all of the lines that are indented under it (lines 12-18) keep on repeating forever.

    Line 13 displays our image variable i  to the micro:bit screen. This is going to be blank the first time the while loop runs but lines 17 and 18 will change the brightness of the bottom row of LEDs so each time it loops after that,  you’ll see random brightness along the bottom.

    Line 14 slows down the program by pausing it for 100ms or 0.1 s

  2. Add the remaining lines of code:
    from microbit import *
    import random
    
    # create an empty image
    i = Image("00000:"*5)
    
    # start with the fire at medium intensity
    intensity = 0.5
    
    # keep looping
    while True:
        # show the image and wait
        display.show(i)
        sleep(100)
        
        # choose random brightness for bottom row of fire
        for x in range(5):
            i.set_pixel(x, 4, random.randint(0,9))
    

    range(5)makes a list that contains the numbers 0, 1, 2, 3 and 4: [0, 1, 2, 3, 4]

    for x in range(5)makes a variable called xand uses it to loop through each value in range(5) , which means it will loop 5 times. The first time round, xwill be 0, then 1, then 2… up until 4

    i.set_pixel()changes the brightness of one LED in our image variable i

    The x coordinate of the LED we’re going to change is our variable x . Because we’re in a for loop that uses xto count from 0 to 4, this means we can change each LED separately from left to right.

    The y coordinate of the LED we’re going to change is always 4. This is the 5th and bottom row of LEDs (0 would be the 1st and top row).

    random.randint(0,9)  chooses a random number between 0 and 9. We use this to set the brightness of the LED.

     

The next page shows you how to make the flames dance up the screen and die down slowly

Leave a Reply