Projects / Mastermind code breaker

Mastermind code breaker

Intermediate1.7 hGuided buildReviewed

Build it step by step

0 of 7 done
  1. NANO

    Wire the buttons

    D2 to D5, other legs to GND.

  2. NANO17.8 mA

    Wire the four LEDs

    D6 to D9, each through a 220 ohm resistor, short legs to GND.

  3. NANO17.8 mASSD1306

    Wire the OLED

    SDA to A4, SCL to A5, 5V and GND.

  4. NANO

    Upload the sketch

    The screen shows Try 0/10 and the best score.

  5. NANO17.8 mA

    Press four buttons

    The LEDs light one by one and your guess shows.

  6. NANO

    Read the clue

    X means right colour and place, O means right colour in the wrong place.

  7. NANO

    Keep guessing

    Until you crack the code or run out of tries.

In short

How do you build a mastermind code breaker?

The Nano thinks of a secret code of four colours, you guess it with four buttons, and it tells you how many are the right colour in the right place and how many are the right colour in the wrong place. Solve it in as few tries as you can. You need Arduino Nano, Tactile push button 6 mm × 4, LED 5 mm red × 4, Resistor 220 Ω × 4, SSD1306 OLED Display, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm). It takes 7 steps and about 100 minutes.

Level
Intermediate
Time
About 100 min
Parts
7

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
Colour buttons 1 to 4Nano D2, D3, D4 and D5 and GNDEach press enters that colour
Progress LED 1 to 4 long legsNano D6, D7, D8 and D9, each through a 220 ohm resistorShows how many colours are entered
LED short legsNano GNDReturn
OLED SDA and SCLNano A4 and A5I2C data and clock
OLED VCC and GNDNano 5V and GNDPower for a 0.96 inch module

Code

The Nano picks four symbols, each from 1 to 4, and repeats are allowed. Put four coloured stickers on the buttons so that 1 to 4 are your four colours. You press four buttons to make a guess, and the four LEDs light one by one to show how many you have entered. After the fourth press the screen shows your guess with X for the number in the right colour and the right place, and O for the number that are the right colour in the wrong place. The scoring counts exact matches first, then adds up how many of each colour appear in both the guess and the secret and subtracts the exact ones, which stops a repeated colour being counted twice. You get ten tries. The best score is stored in the Nano's EEPROM so it survives a power cut, and a value of 255 means no score yet. The random seed is set again on the first press, using the microseconds clock, so every game is different. Install "Adafruit SSD1306" and "Adafruit GFX" from the Library Manager. Try a game with a different number of colours or a longer code, or add a button that gives a hint.

Runs on a virtual Arduino Nano in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

// Libraries: Adafruit SSD1306 and Adafruit GFX.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <EEPROM.h>

Adafruit_SSD1306 oled(128, 64, &Wire, -1);

const uint8_t BTN[4] = {2, 3, 4, 5};
const uint8_t LED[4] = {6, 7, 8, 9};
const uint8_t MAX_TRIES = 10;

uint8_t secret[4];
uint8_t guess[4];
uint8_t entered = 0;
uint8_t tries = 0;
uint8_t best = 255;
bool seeded = false;
bool finished = false;
bool prevDown[4];

uint8_t histGuess[3][4];
uint8_t histExact[3];
uint8_t histPartial[3];
uint8_t histCount = 0;

void newCode() {
  for (uint8_t i = 0; i < 4; i++) secret[i] = random(1, 5);   // repeats allowed
  entered = 0;
  tries = 0;
  histCount = 0;
  finished = false;
}

void score(uint8_t &exact, uint8_t &partial) {
  exact = 0;
  uint8_t common = 0;
  for (uint8_t i = 0; i < 4; i++) if (guess[i] == secret[i]) exact++;
  for (uint8_t c = 1; c <= 4; c++) {
    uint8_t g = 0, s = 0;
    for (uint8_t i = 0; i < 4; i++) {
      if (guess[i] == c) g++;
      if (secret[i] == c) s++;
    }
    common += (g < s) ? g : s;
  }
  partial = common - exact;
}

void draw(const char *msg) {
  oled.clearDisplay();
  oled.setTextSize(1);
  oled.setTextColor(SSD1306_WHITE);
  oled.setCursor(0, 0);
  oled.print("Try ");
  oled.print(tries);
  oled.print("/");
  oled.print(MAX_TRIES);
  oled.print("  Best ");
  if (best == 255) oled.print("-"); else oled.print(best);
  for (uint8_t h = 0; h < histCount; h++) {
    oled.setCursor(0, 14 + h * 10);
    for (uint8_t i = 0; i < 4; i++) { oled.print(histGuess[h][i]); oled.print(' '); }
    oled.print(" X");
    oled.print(histExact[h]);
    oled.print(" O");
    oled.print(histPartial[h]);
  }
  oled.setCursor(0, 48);
  oled.print("Now: ");
  for (uint8_t i = 0; i < 4; i++) {
    if (i < entered) oled.print(guess[i]); else oled.print('_');
    oled.print(' ');
  }
  oled.setCursor(0, 57);
  oled.print(msg);
  oled.display();
}

void showLeds() {
  for (uint8_t i = 0; i < 4; i++) digitalWrite(LED[i], i < entered ? HIGH : LOW);
}

void submitGuess() {
  uint8_t ex, pa;
  score(ex, pa);
  tries++;
  if (histCount == 3) {                        // keep the last three guesses
    for (uint8_t h = 0; h < 2; h++) {
      for (uint8_t i = 0; i < 4; i++) histGuess[h][i] = histGuess[h + 1][i];
      histExact[h] = histExact[h + 1];
      histPartial[h] = histPartial[h + 1];
    }
    histCount = 2;
  }
  for (uint8_t i = 0; i < 4; i++) histGuess[histCount][i] = guess[i];
  histExact[histCount] = ex;
  histPartial[histCount] = pa;
  histCount++;
  entered = 0;
  Serial.print("Try ");
  Serial.print(tries);
  Serial.print(": exact ");
  Serial.print(ex);
  Serial.print(", colour only ");
  Serial.println(pa);

  if (ex == 4) {
    finished = true;
    if (tries < best) { best = tries; EEPROM.update(0, best); }
    for (uint8_t k = 0; k < 4; k++) {
      for (uint8_t i = 0; i < 4; i++) digitalWrite(LED[i], HIGH);
      delay(150);
      for (uint8_t i = 0; i < 4; i++) digitalWrite(LED[i], LOW);
      delay(150);
    }
    draw("Cracked it! Press any");
  } else if (tries >= MAX_TRIES) {
    finished = true;
    char line[22];
    sprintf(line, "Code %d%d%d%d. Press any", secret[0], secret[1], secret[2], secret[3]);
    draw(line);
  } else {
    draw("X right, O wrong spot");
  }
}

void setup() {
  for (uint8_t i = 0; i < 4; i++) {
    pinMode(BTN[i], INPUT_PULLUP);
    pinMode(LED[i], OUTPUT);
  }
  Serial.begin(9600);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  best = EEPROM.read(0);                       // 255 means no score saved yet
  randomSeed(analogRead(A0));
  newCode();
  draw("Press 1-4 to guess");
}

void loop() {
  for (uint8_t i = 0; i < 4; i++) {
    bool down = (digitalRead(BTN[i]) == LOW);
    if (down && !prevDown[i]) {
      delay(20);
      if (!seeded) { randomSeed(micros() ^ analogRead(A0)); newCode(); seeded = true; }
      if (finished) {
        newCode();
        showLeds();
        draw("Press 1-4 to guess");
      } else {
        guess[entered++] = i + 1;
        showLeds();
        if (entered == 4) submitGuess(); else draw("Press 1-4 to guess");
      }
    }
    prevDown[i] = down;
  }
}

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
First pressThe game starts with a new code
Each pressOne more LED lights and the guess appears
Fourth pressA clue appears with X and O counts
Correct codeLEDs flash and the best score updates
Ten wrong triesThe secret code is shown

If it does not work

Blank screen

Check the OLED wires and try address 0x3D.

Same code every game

Check the random seed lines are present.

A button enters twice

Check it is wired across the breadboard gap, not shorted.

LED stays dark

Check its direction and the 220 ohm resistor.

Best score looks odd

Clear it by uploading a sketch that writes 255 to EEPROM address 0.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the mastermind code breaker?

Arduino Nano, Tactile push button 6 mm × 4, LED 5 mm red × 4, Resistor 220 Ω × 4, SSD1306 OLED Display, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm).

How long does the mastermind code breaker take to build?

About 100 minutes for a intermediate maker, in 7 steps.

How do I know the mastermind code breaker works?

First press: The game starts with a new code. Each press: One more LED lights and the guess appears. Fourth press: A clue appears with X and O counts.

Blank screen: what should I check?

Check the OLED wires and try address 0x3D.

Same code every game: what should I check?

Check the random seed lines are present.

A button enters twice: what should I check?

Check it is wired across the breadboard gap, not shorted.

LED stays dark: what should I check?

Check its direction and the 220 ohm resistor.