Source Code

<div class="mm-app">
  <div class="mm-header">
    <h2>Code Breaker</h2>
    <div class="stats">
      <div class="stat"><span class="stat-label">Guess</span><span class="stat-val" id="mm-turn">1/10</span></div>
    </div>
  </div>

  <p class="mm-goal">Crack the 4-peg secret code. Black pegs mean right color, right spot. White pegs mean right color, wrong spot.</p>

  <div class="mm-current" id="mm-current"></div>

  <div class="mm-palette" id="mm-palette"></div>

  <div class="mm-row-actions">
    <button class="ghost-btn" id="mm-clear">Clear</button>
    <button class="solid-btn" id="mm-submit">Submit guess</button>
  </div>

  <p class="mm-feedback" id="mm-feedback">Pick 4 colors, then submit.</p>

  <div class="mm-board" id="mm-board"></div>

  <div class="mm-actions">
    <button class="ghost-btn" id="mm-new">New code</button>
  </div>
</div>

Mastermind Code Breaker Game — Free HTML CSS JS Snippet

Mastermind Code Breaker Game · Games · Plain HTML, CSS & JS · Live preview

What's included

Features

scoreGuess() correctly handles repeated colors using a splice-based two-pass matching algorithm
randomSecret() allows color repeats in the hidden code, matching real Mastermind rules
Palette-based guess building prevents invalid input entirely — no typing or typos possible
Live current-guess slots update as colors are picked, with a filled-state border style
Scrollable guess history shows every past guess with its black/white feedback pegs
Configurable CODE_LENGTH, MAX_TURNS, and COLORS constants for difficulty tuning
Win detection the instant a guess earns a full set of black pegs
Turn-limit loss state with a clear "out of guesses" message

About this UI Snippet

Mastermind Code Breaker Game — Black/White Peg Deduction Logic in Vanilla JS

Screenshot of the Mastermind Code Breaker Game snippet rendered live

Mastermind is a classic code-breaking deduction game: the computer picks a hidden sequence of colored pegs, and the player tries to guess it within a limited number of attempts, receiving black and white peg feedback after every guess. Black means a color is in the exact right position; white means a color exists in the code but in the wrong position. This snippet implements the complete game loop — secret generation, guess building from a color palette, correct peg-counting logic (the trickiest part to get right), a scrollable guess history, and win/lose states — entirely in vanilla JavaScript.

Generating the secret code

randomSecret() picks CODE_LENGTH (4) colors independently at random from the COLORS palette, with repeats allowed — a real Mastermind code can and often does repeat a color, which is part of what makes deduction interesting. The secret is stored in a closured secret array and never rendered to the DOM, so it can't be read from the page source while playing.

The peg-counting algorithm: why a naive comparison is wrong

The subtle part of Mastermind is scoring white pegs correctly when colors repeat. A naive approach that just checks "does this guessed color exist anywhere in the secret" over-counts: if the secret has one red and the guess has three reds, only one white or black peg should be awarded for red, not three. scoreGuess() solves this with a two-pass approach. The first pass counts black pegs (exact position matches) and, for everything else, pushes the *unmatched* secret and guess colors into secretLeft and guessLeft arrays — removing already-matched positions from consideration entirely. The second pass walks guessLeft and, for each color, looks it up in secretLeft with indexOf; if found, it counts a white peg and splices that specific slot out of secretLeft so the same secret peg can never be claimed twice. This splice-on-match step is exactly what keeps repeated colors from being over-counted.

Building a guess from a palette, not a text input

Instead of typing colors, the player clicks swatches in .mm-palette to push colors onto a currentGuess array, rendered live into four .mm-slot circles. This keeps the interaction fast and mirrors the physical board-game experience of placing pegs, and it structurally prevents invalid input (typos, wrong color names) since only real palette colors can ever enter currentGuess.

Feedback pegs and turn limits

After each submitted guess, renderRow() appends a row to the guess history containing the guessed colors and up to four small feedback pegs — black pegs first, then white, then empty placeholders — matching the classic physical presentation. turn increments on every non-winning guess and the game ends in a loss once it reaches MAX_TURNS (10) without four black pegs, or ends in a win the instant score.black === CODE_LENGTH.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this snippet's HTML, CSS, and JS into an AI coding assistant like Claude and ask it to trace through scoreGuess() with a guess and secret that share a repeated color, to see exactly why the splice-based two-pass approach avoids over-counting white pegs. It is also a strong candidate for extension — ask the assistant to add a computer-opponent mode using the classic Knuth five-guess minimax algorithm, add difficulty presets that change CODE_LENGTH and the palette size together, or persist win/loss statistics across sessions with localStorage.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a Mastermind-style code breaker game in plain HTML, CSS, and JavaScript — no libraries, no backend.

Requirements:
- Generate a hidden secret sequence of 4 colors chosen independently at random from a palette of 6 colors, allowing repeats, and never expose it in the rendered DOM.
- Let the player build a guess by clicking color swatches, filling four visible guess slots one at a time, with a way to clear the current guess before submitting.
- On submit, score the guess against the secret using correct Mastermind rules: count a black peg for every position where the guessed color exactly matches the secret color at that position, and count a white peg for every remaining guessed color that exists somewhere else in the remaining (non-black-matched) secret positions — making sure a single secret peg can never be counted toward more than one feedback peg, even when colors repeat.
- Append each submitted guess and its resulting black/white feedback pegs to a scrollable guess history list, most recent guess at the top.
- Limit the game to 10 total guesses. Detect a win the instant a guess scores 4 black pegs, and detect a loss if the guess limit is reached without a win, disabling further input in both cases.
- Add a "New code" button that generates a fresh random secret and resets the turn counter and guess history.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.

Step by step

How to Use

  1. 1
    Click colors to build a guessClick swatches in the palette to fill the four current-guess slots. Click Clear to start the row over.
  2. 2
    Submit the guessOnce all four slots are filled, click "Submit guess" to score it against the hidden secret via scoreGuess().
  3. 3
    Read the feedback pegsBlack pegs mean a color is in the exact right position; white pegs mean a color is in the code but the wrong position. Each color can only be claimed once per row.
  4. 4
    Keep guessing until solved or out of turnsYou get 10 guesses (MAX_TURNS). Getting four black pegs wins immediately; running out of turns ends the round.
  5. 5
    Review the guess historyThe scrollable board below the input keeps every previous guess and its feedback pegs visible, newest at the top.
  6. 6
    Start a new codeClick "New code" at any time to generate a fresh random secret via randomSecret() and reset the turn counter.

Real-world uses

Common Use Cases

Logic and deduction puzzle collections
A genuinely different deduction mechanic from pattern-recall games like Simon — this rewards elimination reasoning across multiple turns rather than memory.
Teaching combinatorics and information theory
Mastermind is a standard teaching example for minimax guessing strategies and information-gain reasoning — this snippet gives students something concrete to reason about immediately.
Reference implementation of multiset matching
scoreGuess() is a clean, readable example of matching two multisets without double-counting shared elements, a pattern that generalizes well beyond games.
Break-time brain teaser in a product
Drop this into an idle dashboard state or waiting screen as a self-contained puzzle with no backend or external dictionary required.
Peg-and-palette UI pattern reference
The circular swatch palette and peg-slot layout is reusable anywhere a UI needs discrete, colorful multi-slot input, such as a theme picker or tag builder.

Got questions?

Frequently Asked Questions

scoreGuess() first counts exact-position matches as black pegs and removes those positions from consideration. It then matches remaining guessed colors against remaining secret colors one at a time using indexOf, and splices each matched secret color out immediately so it cannot be claimed by a second white peg.

Yes. randomSecret() picks each of the four positions independently, so repeats are allowed, exactly like the physical Mastermind board game.

MAX_TURNS is set to 10. If you have not scored a full row of black pegs by your tenth submitted guess, the round ends in a loss and you can start a new code.

No, the secret array is not rendered into the DOM at any point during play, so it cannot be read from the rendered HTML — only from the JavaScript source itself if you inspect the code (as with any client-side game).

Increase CODE_LENGTH for a longer secret, add more entries to the COLORS array for more possible colors per slot, or lower MAX_TURNS to reduce the number of allowed guesses.

No. Each guessed position is classified as black, white, or neither exactly once. A position that scores black is removed from both the secret-left and guess-left pools before white pegs are counted, so it can never also contribute a white peg.