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