Saturday, 19 March 2016

Mastermind


The main purpose of this project was to create an enemy AI for a game that can compete against a real player.
Mastermind is a game in where each player has to guess the opponent's number. The number would consist of 4 digits where none of them are repeated. Every time a player make a guess, you will get clues regarding how good the attempt was. The goal is to find the 4 digits position in the least number of guesses.
The game was created using Visual Studio C++ 2013.


In the Mastermind game you need to keep track of 3 different options for the digits we have guessed already:
  • Digits that we know they are not in the 4 digit's number. We should avoid trying guessing these digits again.
  • Digits that we have guessed in the wrong place. We should try to guess these digits in our next guess, but in a different position that the original ones.
  • Digits that have been guessed in the correct place. We must repeat these digits again in the same position for next guesses.

To make the AI follow these instructions, I thought of 3 different containers for each of them:

  • m_wrongNumbers. A vector that we push_back all digits known not to be in the number.
    We check this container every time the computer tries to guess a number and avoid repeating any of them.
    I chose a vector because is the simplest container where we can just add numbers on it (the order is not important) and iterate thought all of them.
  • m_wrongPlaceList. A list of structs. The struct will contain the digit and an array of 4 bools. Each bool will represent the place where we have guessed this digit already, false for places we haven’t tried yet, true for places we know is not correct.
    We place all digits in this list for next guess, but never on a place we have tried already.
    I chose a list because we need to remove elements, but we don’t know from which position, therefore a list would be more appropriate than a vector, because we might remove elements from the middle of the container.
  • m_rightPlace[4]. An array of 4 chars, we start this array with a 'w' for “wrong” on all positions, if we guess a digit in the correct place, we place that number in that position as a char.
    We place all chars that are not 'w' in that place in all the computer's next guesses.
    I chose an array because we know its going to be of fixed size 4, and we are just going to change its content.

Following these instructions I managed to create a computer opponent that plays the game "perfectly", or at least, without making any mistakes.

You can find my code here.