Computer Play Microbit Programming: Simple Artificial Intelligence Lets Computer Play Games

Introduction to Artificial Intelligence - Let the Computer Play the Game
AI is called artificial intelligence and is often referred to as a computer with human-like intelligence. We can teach Microbit how to play this game. Just use a very simple strategy: move towards the apple (if the apple is above the plate, stay still) . Let's define a function called letComputerPlay.

Then, we can put this function in the main game loop function. We can delete the code that handles the buttons (A and B keys) and provide the corresponding function to move left or right:

function moveLeft() { px--; if (px < 0) px = 4; pixel.setX(px);}) function moveRight() { px++; if (px > 4) px = 0; pixel.setX(px );})
Code and Microbit Simulator:

It worked! Microbit knows how to play the game and it never gets tired. In fact, Microbit is very good at this game.

If you let the Microbit play for a while, you won't see the game over, because in theory the Microbit will always be able to catch the apple, even if it's standing the furthest away - it takes four steps to move, then it takes five steps for the apple to fall to trigger game over!

However, we can still choose a shorter moving direction. Just need to calculate the cost (step size) of moving left or right. This strategy will make the Microbit look smarter. This is an improved version of our MicrobitAI :

function moveLeft() { px--; if (px < 0) px = 4; pixel.setX(px);}) function moveRight() { px++; if (px > 4) px = 0; pixel.setX(px );})
As you can see, we first calculate the cost of left shift costOfMovingLeft and right shift costOfMovingRight, and choose a shorter (better) direction as our policy. In case the cost of left and right is the same, we just choose a random Direction (use Math.randomRange(0, 1) to generate a number of 0 or 1, each with a 50% probability).

Code and Microbit emulator:

As you can see, the artificial intelligence here is very simple – Microbit will play the game strictly according to the instructions of the human. The intelligence of Microbit comes from Decision Making. It is very suitable for computers. The calculation will make decisions based on the current situation, The current situation can often be calculated based on some existing conditions (variables).

PI-SUPPLY is a professional component supplier, providing everything you need for your component project. We also stock a huge selection of Raspberry piArduinomicro:bitrock pi and nvidia manufacturer accessories from your favorite brands.