For this game we need to use the accelerometer to sense the orientation of the micro:bit. This sensor is comprehensively described in the documentation. You find it under “Reference”.
Let’s have a look at one sensor, we choose the accelerometer. It measures acceleration, caused by gravity and sudden movements. Here is a sketch explaing about the three coordinates it uses to put the acceleration into numbers. You can measure the acceleration in on direction (x, y, z) at a time. The values change between -1023 and 1023.
Here is the link accelerometer so that you can have a look.
The documentation is interactive, so you can also upload a sketch to the IDE and run it there. Furthermore, you find examples that you can also easily transfer to the editor, no need to rebuild the projects.
Get to know sensors and how to program them.
Get the examples running on the simulator and your micro:bit. As a next step find the documentation for the magnetic sensor and implement a compass.
Game module
In the micro:bit editor under Advanced you find the category “Game”. It contains blocks to make small games.
The small display of the micro:bit contains 5 x 5 LEDs. In the game module you can address each LED with its coordinates (x, y). You may know coordinate systems from school, they have their origin (0,0) always at the lower left corner. In computer science we normally put the origin at the upper left corner.
Create your first game
Following you find the beginnings of a small game. At the beginning of the game a LED will light up at a random location. Then the player needs to move the other LED to that location using the buttons A and B. When he reaches the final position, the display shows “Win!”. The button A is already coded, try to understand what is happening when you press the button. Then finish the game by coding the functionality for button B.
let dir_x = 0 let sprite2: game.LedSprite = null let sprite1: game.LedSprite = null sprite1 = game.createSprite(2, 2) sprite2 = game.createSprite(Math.random(5), Math.random(5)) dir_x = 1 basic.forever(() => { if (sprite1.isTouching(sprite2)) { basic.showString("Win!") } }) input.onButtonPressed(Button.A, () => { if (sprite1.isTouchingEdge()) { dir_x = dir_x * -1 } sprite1.change(LedSpriteProperty.X, dir_x) }) input.onButtonPressed(Button.B, () => { })
Above is the code in Javascript, open the micro:bit Javascript editor, select “{}Javascript” and then copy and paste the code into the editor. Next, select “Blocks” and the code will be converted into the Block language. Here you can now
- try out the program,
- figure out what is happening when you press Button A and
- then add the missing functionality for button B.
Recent Comments