How to write Mastermind in Javascript?

Jacob Wagner
2 min readFeb 6, 2021

The first decision to be made is about the display: do you want to play in the console using node or do you want to populate a web page that hosts your game? While both options are viable, I chose the latter. The HTML and CSS that I wrote are very minimalistic, and most of the heavy lifting is done in Javascript.

The most important thing to understand with Javascript is the DOM (Document Object Model) and how it differs from the source code. A browser takes your HTML and CSS and creates the DOM — this is actually what is displayed on the screen. You can modify the DOM to change the content of the webpage without it affecting the source code at all. To create the gameboard, all you need to do is update the DOM with your new elements. In Javascript, it is as simple as calling document.createElement() and then using element.appendChild() to put your new element inside an existing one.

Now that you have a gameboard, it needs to be able to do something — that is where Event Listeners come into play. Before we add our elements to the DOM, we can call element.addEventListener() to describe what should happen when certain events affect our element. The two Event Listener categories I used were click and contextmenu, allowing me to add behaviour when you left and right click my elements, respectively. The functions I placed inside these Event Listeners change the background color of the element following the sequence red > blue > yellow > green > black > white, where a left click would cycle forwards through this list of colors while a right click would cycle backwards. This is how you actually play Mastermind, this logic alone allows the player to make their guesses!

Now just some circles with colors means nothing to our program in its current state. To fix this, I added a submit button that handles the majority of the game logic. Inside the Event Listener for a left click on my submit button, I do several things:

  1. Convert the background colors of the 4 circles in a row into a list of colors.
  2. Using this list, I handle the feedback pegs, turning the proper amount of pegs red or white accordingly.
  3. I then check if the guess is actually 100% correct. If it is, game over!
  4. If not, the game advances 1 row to allow for another guess.
  5. If there are no more rows, you lose! Game over!

The last thing I added was a New Game button, that wipes the DOM clean and rebuilds it from scratch, along with generating a new random code to guess against. And that is how you write Mastermind in Javascript! Try it here: https://jwowsquared.github.io/

--

--

Jacob Wagner
0 Followers

Holberton student and aspiring Software Engineer.