More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

BBC micro:bit – The Queen’s Cupcake

microbit-queen-cupcake-1In this challenge we will create a game for the BBC micro:bit.

Imagine you have been asked to bring a cupcake to Her Majesty the Queen Elizabeth II. You have picked the best cupcake from the kitchen and placed it at the centre of a silver tray.

You will have to carry the cupcake on its tray to the Queen, walking through the many rooms and corridors of Buckingham Palace.

Watch out, if you tilt the tray, you may end up dropping the Queen’s cupcake!

microbit-queen-cupcake-2

For this challenge we will replace the silver tray with a BBC micro:bit. The cupcake will be a sprite positioned in the centre of the LED screen, the tray will be the grid of 5×5 LEDs on the micro:bit.

microbit-queen-cupcake-3

The player will have to carry the micro:bit flat on the back of their hand, and carry it around the room, making sure they keep it as flat as possible.

Our program will use the built-in accelerometer input sensor of the micro:bit to find out if the micro:bit is leaning (forward, backward, to the left or to the right).

If so the sprite (cupcake) will slide in the right direction (The LED light will move on the 5×5 grid).

The game will end when/if the cupcake is at the edge of the 5X5 LED grid and the micro:bit is still tilted: the cupcake is falling off the grid/tray.

Video Demo


The Code


You will need to use the micro:bit website to create the code using the JavaScript Block Editor.

micro-bit-logo

the-queen-cupcake-javascript-code

Code Review


Checking the code above answer the following questions:

  • Can you identify the block of code used for the micro:bit to detect if it has been tilted to the left?
  • Can you identify the block of code used for the micro:bit to know when the cupcake is falling off the tray?
  • Can you explain how does the microbit decide to stop the game by running the last block to display the Game Over message?
  • Can you explain the purpose of the variable called tolerance?
    • Why do we need a tolerance?
    • What would be the impact on the game if the tolerance with 500 instead of 200? (Would it be easier to play or harder? Why?)
    • What would be the impact on the game if the tolerance with 50 instead of 200? (Would it be easier to play or harder? Why?)

Extension Task 1


Add some more code to this game to record how long the player/waiter took to deliver the cupcake.

The micro:bit should record the running time from the start (just after the “3-2-1-Go” message) and allow the user to stop the game when they press button A.

The player will have to follow a set route (e.g. around the classroom) and if they manage to complete the route without dropping the cupcake, they should press button A to stop the counter, and the micro:bit should display their time.

Extension Task 2


Tweak the code so that if a player has been playing for 10 seconds without dropping the cupcake, the tolerance then changes to make the game harder to play (e.g. tolerance change from 200 to 100)

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

BBC micro:bit – Tetris Game

For this challenge we are creating a game of Tetris to play on the BBC micro:bit.

The game will be based on the following four shapes:
microbit-tetris-shapes

The game will use the following inputs:

  • Button A: Move current brick to the left
  • Button B: Move current brick to the right
  • Button A and B simultaneously: Rotate current brick clockwise

Video Demo


The game will use the LED screen which consists of a 5×5 grid of 25 LEDs.
Each LED can be on (value: 9 for maximum brightness) or Off (value: 0)
The side/borders of the grid will note be displayed.

The Python code will use 2-dimension arrays (list of lists in Python) to store the main grid (7×5) and the current brick (2×2)
microbit-tetris-grid

microbit-tetris-4-shapes

microbit-tetris-grid-LEDs
To test this code you will need to use the Python Editor from the micro:bit website.
micro-bit-logo

Python Code

from microbit import *
from random import choice

#Set up the tetris grid
grid=[[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,1,1,1,1,1,1]]
#Store a list of 4 bricks, each brick is a 2x2 grid
bricks = [[9,9],[9,0]],[[9,9],[0,9]],[[9,9],[9,9]],[[9,9],[0,0]]
#select a brick randomly and position it at the center/top of the grid (y=0,x=3)
brick = choice(bricks)
x=3
y=0
frameCount=0

#A function to return the maximum of two values
def max(a,b):
    if a>=b:
        return a
    else:
        return b
        
#A function to hide the 2x2 brick on the LED screen
def hideBrick():
    if x>0:
        display.set_pixel(x-1,y,grid[y][x])
    if x<5:
        display.set_pixel(x+1-1,y,grid[y][x+1])
    if x>0 and y<4:
        display.set_pixel(x-1,y+1,grid[y+1][x])
    if x<5 and y<4:
        display.set_pixel(x+1-1,y+1,grid[y+1][x+1])
        
#A function to show the 2x2 brick on the LED screen
def showBrick():
    if x>0:
        display.set_pixel(x-1,y,max(brick[0][0],grid[y][x]))
    if x<5:
        display.set_pixel(x+1-1,y,max(brick[0][1],grid[y][x+1]))
    if x>0 and y<4:
        display.set_pixel(x-1,y+1,max(brick[1][0],grid[y+1][x]))
    if x<5 and y<4:   
        display.set_pixel(x+1-1,y+1,max(brick[1][1],grid[y+1][x+1]))

#A function to rotate the 2x2 brick
def rotateBrick():
    pixel00 = brick[0][0]
    pixel01 = brick[0][1]
    pixel10 = brick[1][0]
    pixel11 = brick[1][1]
    #Check if the rotation is possible
    if not ((grid[y][x]>0 and pixel00>0) or (grid[y+1][x]>0 and pixel10>0) or (grid[y][x+1]>0 and pixel01>0) or (grid[y+1][x+1]>0 and pixel11>0)):
        hideBrick()        
        brick[0][0] = pixel10
        brick[1][0] = pixel11
        brick[1][1] = pixel01
        brick[0][1] = pixel00
        showBrick()     

#A function to move/translate the brick
def moveBrick(delta_x,delta_y):
    global x,y
    move=False
    #Check if the move if possible: no collision with other blocks or borders of the grid
    if delta_x==-1 and x>0:
        if not ((grid[y][x-1]>0 and brick[0][0]>0) or (grid[y][x+1-1]>0 and brick[0][1]>0) or (grid[y+1][x-1]>0 and brick[1][0]>0) or (grid[y+1][x+1-1]>0 and brick[1][1]>0)):
            move=True
    elif delta_x==1 and x<5:
        if not ((grid[y][x+1]>0 and brick[0][0]>0) or (grid[y][x+1+1]>0 and brick[0][1]>0) or (grid[y+1][x+1]>0 and brick[1][0]>0) or (grid[y+1][x+1+1]>0 and brick[1][1]>0)):
            move=True
    elif delta_y==1 and y<4:   
        if not ((grid[y+1][x]>0 and brick[0][0]>0) or (grid[y+1][x+1]>0 and brick[0][1]>0) or (grid[y+1+1][x]>0 and brick[1][0]>0) or (grid[y+1+1][x+1]>0 and brick[1][1]>0)):
            move=True
    #If the move is possible, update x,y coordinates of the brick
    if move:      
        hideBrick()
        x+=delta_x
        y+=delta_y
        showBrick()
        
    #Return True or False to confirm if the move took place
    return move    

#A function to check for and remove completed lines
def checkLines():
    global score
    removeLine=False
    #check each line one at a time
    for i in range(0, 5):
        #If 5 blocks are filled in (9) then a line is complete (9*5=45)
        if (grid[i][1]+grid[i][2]+grid[i][3]+grid[i][4]+grid[i][5])==45:
            removeLine = True
            #Increment the score (10 pts per line)
            score+=10
            #Remove the line and make all lines above fall by 1:
            for j in range(i,0,-1):
                grid[j] = grid[j-1]
            grid[0]=[1,0,0,0,0,0,1]    
    if removeLine:
        #Refresh the LED screen
        for i in range(0, 5):
            for j in range(0, 5):
                display.set_pixel(i,j,grid[j][i+1])
    return removeLine
    
gameOn=True
score=0
showBrick()
#Main Program Loop - iterates every 50ms
while gameOn:
    sleep(50)
    frameCount+=1
    #Capture user inputs
    if button_a.is_pressed() and button_b.is_pressed():
        rotateBrick() 
    elif button_a.is_pressed():
        moveBrick(-1,0)
    elif button_b.is_pressed():
        moveBrick(1,0)
    
    #Every 15 frames try to move the brick down
    if frameCount==15 and moveBrick(0,1) == False:
        frameCount=0
        #The move was not possible, the brick stays in position
        grid[y][x]=max(brick[0][0],grid[y][x])
        grid[y][x+1]=max(brick[0][1],grid[y][x+1])
        grid[y+1][x]=max(brick[1][0],grid[y+1][x])
        grid[y+1][x+1]=max(brick[1][1],grid[y+1][x+1])
        
        if checkLines()==False and y==0:
            #The brick has reached the top of the grid - Game Over
            gameOn=False   
        else:
            #select a new brick randomly
            x=3
            y=0
            brick = choice(bricks)
            showBrick()
    
    if frameCount==15:
       frameCount=0

#End of Game
sleep(2000)
display.scroll("Game Over: Score: " + str(score)) 

Note: When testing this code, you may want to remove some of the #annotations especially if your micro:bit returns a “memory full” error.

Tagged with:

BBC micro:bit – Rock Paper Scissors Game

rock-paper-scissorsFor this challenge you need to code your micro:bit so that when you shake the micro:bit a picture appears randomly.

There should be three possible pictures:

  • A picture of a rock,
  • A picture of a pair of scissors,
  • A picture of a paper sheet.

Download your code to your micro:bit and play the game with your friends, using one micro:bit per player.

Use will need to use the BBC micro:bit website to code this game.
micro-bit-logo

Solution


Extension Task


Reuse and adapt your code to transform your BBC micro:bit into a dice. Your code will need to generate a random number (between 1 and 6) and based on the value of this number display (using the LEDs) the corresponding face of the dice:
dice-faces

Tagged with:

BBC micro:bit – Higher or Lower Game

For this challenge you will design and write a program to play against the BBC micro:bit.

The micro:bit will display a random number between 0 and 100. It will then ask the end-user whether they believe the next number will be higher or lower. The program will then generate the next number. If the user guessed right (e.g. the next number is higher or lower than the previous one) then the user scores one point. The game stops when the user guesses it wrong.

micro-bit-higher-or-lower-5

Learning Objectives

By completing this challenge you are going to use selection (IF statements) and comparison operators such as >= or <= to compare numbers. You will also use variables to store the value of random numbers, and to keep and increment a score as the game progresses.

Solution


Try to implement the game by yourself on the BBC micro:bit website:

micro-bit-logo

If you are stuck you can always use our solution below:

Step 1: Initialising the game
For our game we will need three variables:

  • number: the current number, randomly selected (between 0 and 100) being displayed on the LED screen,
  • nextNumber: the next number, also randomly selected between 0 and 100, but kept secret, the user will decide if they beieve it will be higher or lower than the current number,
  • score: the score will start at 0 and increment by 1 everytime the user has a good guess.

micro-bit-higher-or-lower-1

Step 2: Button A: Lower
When the user presses button A, they believe the next number will be lower than the current number. We can check if they are right or not.

If they are correct, we will display a smiley face, add 1 to their score and the nextNumber will become the current number whereas a new nextNumber is generated for the game to continue.

If they are wrong though, we will display a sad face as well as the value of the next number followed y the user score.micro-bit-higher-or-lower-2

Step 3: Button B: Higher
Step 3 is very similar to step 2 but this time we are checking whether the next number is higher than the current number.micro-bit-higher-or-lower-3

Extension Task:


That’s it you have a fully working game. We can tweak it slightly though. For instance how could we code the micro:bit so that when the user presses both the A and B buttons at the same time, the game restarts from the beginning – a new set of numbers is generated and the score is reset to zero?

Tagged with:

Archery Scoring Algorithm

archeryIn this challenge we will write a Python program to randomly shoot an arrow on a target. We will then use Pythagoras’ Theorem to calculate the distance between the arrow impact and the centre of the target. This distance will let us find out how many points to award to this shoot.

Scoring System


For our program we will be using the following scoring system:
archery-target

Pythagoras’ Theorem


The arrow will be issued (x,y) coordinates randomly. Our script will use these coordinates to calculate the distance of the arrow from the centre of the target (0,0).

archery-pythagoras

With this distance we can then decide how many points to be given using the following criteria:

  • Distance between 0 – 30 pixels (Yellow Ring) = 10 points
  • Distance between 31 – 60 pixels (Red Ring) = 5 points
  • Distance between 61 – 90 pixels (Blue Ring) = 3 points
  • Distance between 91 – 120 pixels (Black Ring) = 2 points
  • Distance between 121 – 150 pixels (White Ring) = 1 point
  • Distance above 150 pixels (Off Target) = 0 point

The code so far…


As you can see we have started the code for you below but still have work to do on line 44 to 54 to calculate the distance of the arrow from the centre of the target and calculate the score.

You challenge is to complete this code (line 44 to 54).

Extension Task


Can you let the computer shoot three arrows and display the total score of all three arrows, by adding the score of each arrow.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

BBC micro:bit – Roll the Dice

diceIn this challenge we will code our BBC micro:bit to create a “rolling dice” animation.

Our code will generate random numbers between 1 and 6 to create the animation and will include 8 frames. The last frame will be the number picked up by the dice. Here is a preview of the animation (on an infinite loop):

bbc-micro-bit-roll-the-dice

You can recreate this digital dice using the BBC micro:bit website.

Building the code, step by step:

Our “rolling the dice” animation will start when the user presses the A button on the micro-bit.
micro-bit-button-a

To create the animation we will then use a loop (repeat 8 times):
micro-bit-repeat

For each frame we will generate a random number between 1 and 6 using the following code:
micro-bit-random-number

We will then check the value of this random number using an IF block:
micro-bit-if

To display this number as it will appear on a dice we will use the “show leds” block:
micro-bit-show-leds

We will repeat the last two steps for all the 6 possible faces of the dice by adding ELSE IF blocks to our IF block:
micro-bit-else-if

Finally we will add a pause between each frame (between each iteration of the loop):
micro-bit-pause

Final Code


Here is the complete code for our dice:
micro-bit-die-code

Tagged with:

BBC micro:bit – Digital Compass

compass-iconIn this challenge we will use the compass sensor from the BBC micro:bit to create a digital compass.

Based on the compass heading (retrieved ftom the sensor), the micro:bit will display one of the four cardinal points:

  • N for North
  • E for East
  • S for South
  • W for West

For the micro:bit to decide which cardinal point to display it will have to look at the compass headings (angle given in degrees).

Check the following pictures to understand how angles and cardinal points work:
compass-full

cardinal-points

Heading (in degrees) Cardinal Point
Between 315° and 360°
OR
Between 0° and 45°
North
Between 45° and 135° East
Between 135° and 225° South
Between 225° and 315° West

Coding the compass


Access the micro-bit website:
micro-bit-logo

Use the Block Programming interface to add the following code (click on picture to zoom in):
digital-compass-bbc-microbit-javascript-code

Calibrating the compass


The first time you will run this program, the BBC micro:bit will ask you to “Draw a circle”.

This step is required to calibrate the compass. Without this step the readings would be inaccurate.

To draw the circle on the LED display simply rotate the device to move “the light” around the LED screen and display a circle as follows:

micro-bit-circle .

Tagged with:

BBC micro:bit – Magic 8 Ball

For this project we are going to code our micro:bit to act as a magic 8 ball:
magic-eight-ball

The user will think of a question such as:

  • Will it be snowing tomorrow?
  • Will I be a rock star one day?
  • Will my program work?

Then they will shake the micro-bit. The micro-bit will than randomly pick one of the following four answers:

  • No way!
  • Probably!
  • Unlikely!
  • Definitely!

Have a go at completing the task by yourself and if you get stuck or don’t know how to get started check our solution below.

Access BBC micro:bit website:
micro-bit-logo

Solution


Extension Task


Tweak the code to add more possible answers such as:

  • I don’t think so
  • Maybe
  • No doubt about it
  • Not sure
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

BBC micro:bit – Ticketing System

Now-ServingYour challenge consists of programming your BBC micro:bit to use it as a ticketing system. Ticketing systems are used in a shop to control the order of the queue of customers:

  1. The queue should start at the value 0, and should be displayed on the micro:bit LED screen.
  2. When a shop assistant is available they press button A to call for a customer: The queue number displayed on the micro:bit should increase by 1.
  3. The shop assistant should be able to cancel their action by pressing button B: in this case the queue number should decrease by 1.
  4. To reset the ticketing system, the shop assistant should press both A and B buttons simultaneously. The queue number will be reset to 0.

queue

Solution


Tagged with:

What’s My Change?

my-change

Your Challenge


Using either Python or HTML + JavaScript, write a program that prompts the end-user to enter two values:

  • Value 1: Amount to be paid by the customer
  • Value 2: Amount received from the customer

The program should then find out how many banknotes or coins of different values should be returned.
what-s-my-change

Tip:


Your program will accept banknotes of £20, £10 and £5 and the following coins: £2, £1, 50p, 20p, 10p, 5p, 2p, 1p.

The following flowchart will help you get started:
what-s-my-change-flowchart

Extension:


Add some validation rules to ensure that the user has entered valid currency values. You should also check that the amount received from the customer is greater or equal to the amount to be paid.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,