In this lesson we will create a game on the Microbit to display a random number between 1 and 100. Using the A and B buttons on the Microbit, the player has to guess if the next number will be higher or lower. See who can get the highest score!
Go to the Makecode.com Microbit website using the link below and click on the 'New Project' button underneath the 'My Projects' heading.
Install the micro:bit app on your iPad or tablet.
Open the app, tap 'Create code' and then create a new project.
Create 2 new variables called 'number' and 'nextnumber'.
We will use these to store the number that displays on the screen and the next number that the player needs to guess if it's higher or lower.
In the Variables toolbox, create a new variable by clicking the 'Make a Variable' button.
Once you click this button a box will appear asking what you want to call your variable. Give it a name that reminds you what you will be using it for. For example, if you wanted to keep track of your score in a game, you would create a variable called 'score'.
At the start of the game we're going to set the 'number' variable to a random number between 1 and 100, and we'll also set the 'nextnumber' variable to a random number between 1 and 100.
Once we've set the numbers we'll display the 'number' variable on our Microbit.
Add the following code.
let number = randint(1, 100) let nextnumber = randint(1, 100) basic.showNumber(number)
To play the game, the player needs to guess if the next number will be higher or lower than the number that's currently being displayed.
To guess lower they will press the A button, to guess higher they will press the B button.
Program the A button to guess lower
Add the following code to program the A button to:
input.onButtonPressed(Button.A, function () { basic.pause(500) if (nextnumber <= number) { basic.showIcon(IconNames.Yes) } else { basic.showIcon(IconNames.No) } })
If the player guesses correctly that the next number is lower, then as well as displaying the correct icon we will give them a point.
Add the following new code underneath the correct show icon block.
input.onButtonPressed(Button.A, function () { basic.pause(500) if (nextnumber <= number) { basic.showIcon(IconNames.Yes) basic.pause(1000) game.addScore(1) basic.pause(1000) } else { basic.showIcon(IconNames.No) } })
You will find the change score by 1 block in the Advanced > Game toolbox. This block plays a little flash animation and adds 1 point to your score.