I made the game Mastermind using C++ and would like anyone who wants to test it and let me know what they think. It comes with instructions, but since I wrote them and I know how to play the game, they might not be clear.

Note: If this post is not supposed to go here feel free to delete or whatever. If there is a better place for stuff like this to go, please let me know.

#include <iostream>
#include <ctime>    // For time()
#include <cstdlib>  // For srand() and rand()

using namespace std;

void displayIntro();
void prompt(char guess[], int n);
bool gaveOver(char guess[], char right[]);
char convertToColor(int num);

// #######################################################
int main(void)
{
    char symbol;
    char guess[4];
    char right[4];
    bool playAgain = true;
    bool won;
    int numGuesses;
    
    displayIntro();
    
    while (playAgain) {
          won = false;
          numGuesses = 10;
          
          cout << endl;
          // generate the correct random sequence
          srand(time(0));
          for (int i = 0; i < 4; i++)
          {
              int temp = (rand() % 6) + 1;
              right[i] = convertToColor(temp);
              //cout << right[i] << " ";
        }
        cout << endl;

        // loop until the user gets the right value    
        while (!won && numGuesses > 0)
        {
              prompt(guess, numGuesses);
              won = gaveOver(guess, right);
              numGuesses--;
        }
                          
        if (won)
        {
           cout << "You win! The correct sequence was " << right[0] << " "
                << right[1] << " " << right[2] << " " << right[3] << endl;
        }
        else
        {
            cout << "You lost! The correct sequence was " << right[0] << " "
                 << right[1] << " " << right[2] << " " << right[3] << endl;
        }
           
        cout << "Would you like to play again (Y or N): ";    
    
        cin >> symbol;
           
        playAgain = (symbol == 'Y' || symbol == 'y') ? true : false;
    }
    
    return 0;
} // end main

// #######################################################
bool gaveOver(char guess[], char right[])
{
     int totalRight = 0;
     int rightColor = 0;
     int grab;
     bool exclude[4];
     bool excludeColor[4];
     bool inList = false;
     
     for (int i = 0; i < 4; i++)
     {
         exclude[i] = false;
         excludeColor[i] = false;
     }
     
     // loops to determine which have both the correct color and position
     for (int i = 0; i < 4; i++)
     {
         if (guess[i] == right[i])
         {
            totalRight++;
            exclude[i] = true;
         }
     }
     
     // loops to determine if any colors are correct, just in the wrong position
     for (int i = 0; i < 4; i++)
     {
         if (!exclude[i])
         {
            for (int j = 0; j < 4; j++)
            {
                if (!exclude[j] && i != j)
                {
                   if ((guess[i] == right[j]) && !excludeColor[j]) 
                   {
                      inList = true;
                      grab = j;
                   }
                }
            }
            
            if (inList)
            {
               rightColor++;
               inList = false;
               excludeColor[grab] = true;
            }
         }
         
         
         
     }
     
     if (totalRight == 4)
        return true;
     else 
     {
        cout << totalRight << ", " << rightColor << endl;
        return false;
     }
          
} // end gameOver


// #######################################################
void prompt(char guess[], int n)
{
     cout << "Enter your guess (" << n << "): ";
     
     cin >> guess[0] >> guess[1] >> guess[2] >> guess[3];
     
     
     for (int i = 0; i < 4; i++)
     {
         if (guess[i] > 91) // lower case level
            guess[i] = guess[i] - 32;
     }
     
} // end prompt

// #######################################################
char convertToColor(int num) 
{
     switch (num)
     {
            case 1:
                 return static_cast<char>(66);
            case 2:
                 return static_cast<char>(71);
            case 3:
                 return static_cast<char>(79);
            case 4:
                 return static_cast<char>(80);
            case 5:
                 return static_cast<char>(82);
            case 6:
                 return static_cast<char>(89);
     }
} // end convertToColor

// #######################################################
void displayIntro()
{    
    cout << "======================= Welcome to Mastermind =======================" << endl;
    cout << "Mastermind is a game of logic." << endl;
    cout << "The goal is to use logic to guess the correct four color combination" << endl;
    cout << "by using your previous guesses as clues." << endl;
    cout << "Everytime you guess, you will be told how close to the goal you are." << endl;
    cout << "The first number says how many were in the right place. " << endl;
    cout << "The second number says how many of the right colors you have in the wrong place.";
    cout << "To guess, enter the first letter of each color." << endl;
    cout << "Available colors are Blue, Green, Orange, Purple, Red and Yellow." << endl;
    cout << "An sample guess would be look like this: R R G B" << endl;        
    cout << "====================================================================="; 
}

Recommended Answers

All 3 Replies

Game works great! I tested it and ended up playing it for far longer than I intended. It seems to work fine. The only thing I'd change, if you wanted to improve it, is to have some data validation, as in if users enter in illegal characters or not exactly four characters, the game tells them what they did wrong and prompts them to guess again. Also, you only need to seed the random number generator once. Right now you do it every game in your while loop. Just seed it once at the top. Other than that, perfect.

Well, I already added support for upper and lower case. Do you have any ideas for fixing if the user doesn't insert four characters? I haven't used C++ for very long, and as of now the program will keep on asking for characters until there are four, even if the user presses enter after every time they enter a character.

Thanks for the suggestion about seeding random numbers, I'll change that too.

Well, I already added support for upper and lower case. Do you have any ideas for fixing if the user doesn't insert four characters? I haven't used C++ for very long, and as of now the program will keep on asking for characters until there are four, even if the user presses enter after every time they enter a character.

Thanks for the suggestion about seeding random numbers, I'll change that too.

If the user enters MORE than 4 characters, there is a definite problem because those characters are stored in the buffer. Try entering "bbbbbbbb" and you'll notice that the computer doesn't wait for your answer on the next question because it takes the last four b's as the answer, even though you typed them in response to an earlier question.

If you want to check for valid input, I would read it in as a string. First check, make sure it's exactly four characters using the length function. If not, give an error message. You can also use the toupper function to convert from lower to upper case. Right now you are subtracting 32, which works too. Then you can go through the 4 characters and make sure they are each one of the six legal characters, and if any of those tests fail, display an error message and prompt the user to try again. If they all work, convert the string to a char array and return from your prompt function.

It's extra work and you'll have to decide whether it is worth it, but it might make it a better game since if the user accidentally types in 5 characters or something and doesn't notice, it could be very frustrating since he could type in the correct answer on a line, but the program would say it was wrong because of the leftover characters. Another way to solve that particular problem would be to flush the buffer after each guess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.