The Mastermind Game

Click here to download the Java source code (mastermind.java) which you are welcome to change as you think fit.
Click here to download the Java class file which you can include on your own web site with my blessing (mastermind.class)

What's this all about?

Mastermind is a game involving a series of coloured pegs, and was very popular in the 1970s. It is a game played by two people - the chooser and the guesser. The chooser chooses a combination of four coloured pegs from six colours (Red, Yellow, Green, Blue, Grey and Pink) - say Red, Red, Yellow, Pink, and hides this from the guesser. The guesser has to work out what this combination is from the clues that the chooser gives him/her.

The guesser makes a stab at what the combination is - say Yellow, Grey, Green, Pink. The chooser then awards a black peg for every correct colour in the correct place, and a white peg for every correct colour that is in the wrong place. The guesser then tries another combination, getting another score, and so on until the combination is guessed (an award of 4 black pegs).

Here are some examples: let's suppose the chooser has chosen the following combination: ,

The pink peg is in the right position, and the yellow peg is correct but in the wrong position, so this try is awarded a black peg and a white peg.
There are no blue pegs in the chosen combination, so this try gets nothing.
The chosen combination does contain a pink spot, but it is in neither the first nor the last space. This try gets one (not two) white pegs.
Hooray! This combination matches the chosen combination exactly, so it is awarded four black pegs. At this point, the game would finish.

But what has this got to do with Artificial Intelligence (AI)?

This is more than just an excuse to play games. When the computer tries to discover the pattern that you have chosen, it uses a technique in AI called Generate-and-Test. G-and-T (it sounds like a drink, doesn't it!) works as follows:

In this case, the list of possible solutions is all the possible colour combinations. The restrictions are the scores that the human player awards. The program should initially generate a list of 6 x 6 x 6 x 6 = 1296 patterns. In fact, the program can save a bit of space and processing time by presenting the human player with a randomly chosen pattern and only generating the patterns which are compatible with the score that the human awards the initial pattern. In practice, this means less than 700 patterns in the initial list.