Today you are coding on the micro:bit. You will build a Higher or Lower chance game step by step: a number appears, you guess whether the next one is higher or lower with the buttons, and you try for a strong score.
You can already use the micro:bit editor and simple inputs. This lesson adds random numbers and decisions so the game can check each guess.
Before you run anything, think: when the micro:bit picks two numbers from 1 to 100, what should happen if you press A for lower and you are right? What if you are wrong?
Keep the start short. Devices on, MakeCode micro:bit ready. Frame PRIMM: predict, then build, run and fix. Optional predict: before anyone runs code, ask what should happen on a correct lower guess versus a wrong one. Pairs, not typed answers. Move quickly into the build.
Go to the https://makecode.microbit.org website and create a new project.
Ensure every student or pair has a new MakeCode micro:bit project named the class way. Model opening the site and creating the project on the board. Watch for students editing an old project by mistake.
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.
Model creating both variables, number and nextnumber, with exact spelling. Ask why the game needs two values, not one. Differentiation: strugglers copy the names from the board before continuing.
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)
Model on-start: both variables set to random 1 to 100, then show number. Key question: why show number but not nextnumber yet? Common bug: random range typed wrong or show placed outside on start. Run once so everyone sees a starting 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)
}
})
Build the A-button lower path together: short pause, then compare nextnumber with number. Ask what less than or equal means for a lower guess. Watch for the comparison flipped or the pause missing so the icon flashes too fast.
You're previewing this lesson. Get full access to this lesson and hundreds more — each one ready to teach, with interactive activities, printable resources and pupil progress tracking built in.