Mastermind game for micro:bit

Following my calculator and communicator projects, I decided to recreate the classing 70s game Mastermind on the micro:bit.

Mastermind was based on an older game, possibly called Bulls and Cows or Moo! There have been various computer versions of it over the years, and this is mine. It’s based on guessing numbers. Here’s how to play:

  • The micro:bit thinks up a random 4 digit number which you have to guess.
  • Each digit is unique and there are no zeros.
  • You type in your guess and press D.
  • The micro:bit tells you how many bulls you have – a bull is the right number in the right place. Then it tells you how many cows you have, a cow being a correct number in the wrong place. (Sorry about the sexist bovine terminology, but I can’t think of a better short word to explain it – if you can think of a better pair of names, I’d love to change it!).
  • Use deduction (and luck!) to improve your guesses and work out the secret number.
  • When you do guess it, the micro:bit tells you how many turns it took you.
  • If you give up, there is a cheat mode: press buttons A+B together.

The video explains more about how it works but it’s worth calling out two bits of code that I think are moderately neat.

unique number generation code blocks

These blocks create a 4 digit random number string with unique digits. It uses a while loop which keeps executing until the string is 4 characters long. It picks a random number and if that number is not already in the string, it adds it. When the string reaches 4 characters in length the loop finishes.

counting bulls and cows code

This function counts bulls and cows. It uses a for loop. The first character in a string is at position zero, so starting at 0 is fine. It compares each digit in position in your guess with the digit in the same position in the target number. If they match, that means it’s the right number in the right place, which is a bull, so we increase the bull counter by 1.

If it’s not a bull, then that digit may be a cow, so it then checks to see if the string contains that digit. We don’t need to worry that bulls will also be counted as cows as we’ve already excluded the bull in the first part of the if… statement.

The MakeCode project is below if you want to build your own or explore the code and perhaps improve it. See the communicator project for details of how to connect a 4×4 keypad to your micro:bit – you just need the keypad, 8 female to male jumper wires and a breakout board for the micro:bit.

This entry was posted in microbit and tagged , , . Bookmark the permalink.

Leave a Reply