Hello,

I am writing code that mimics the game Mastermind. The computer randomly comes up with a code based on the "colors" RGBOY. The user has ten guesses to guess what the code is. Right now my code displays the secret code at the beginning just so I can test it out, but it will not display the secret code in the final until the end if the user has not guessed it.

The game gives feedback based on the user's guesses. For example, if the secret code is GBYO and the user enters GBOY, the feedback will be 1100. The first two colors are in the correct place and order, while the last two are the correct colors, but NOT in the correct order. I have written code that does this.

BUT for some reason, if the first code entered is not automatically the right one, the first time I loop through and encounter my displayFeedback function, it is missing a character in the feedback! But if I enter the SAME guess on the second guess, the feedback is correct!!! I am attaching an image so you can see what I mean. I am also posting my code. Does ANYONE have any idea why it would be doing this? The feedback works correctly from plays 2-10, but for some reason that first time through it does not! Any suggestions would be great.

http://i631.photobucket.com/albums/uu33/lupwned/mastermind.png < Print Screen

#include <iostream>
#include <string>
#include <ctime>

using namespace std;

// Prototypes

void setSecretCode(char[]);
void displaySecretCode(char[]);
void removeColor(char[], string &, int);
void getGuess(char[][4], int, int);
void displayFeedback(char[][4], char [], int, int, char [][4]);
bool isItWin(char [][4], char [], int);

// Main
int main()
{
    // Define Variables
    char code[4];
    const int SIZE = 10;
    char guess[SIZE][4];
    char feedback[SIZE][4] = {0};
    bool winner;
    int i = 0;
    int j = 1;
    // Call Set Secret Code
    setSecretCode(code);
    displaySecretCode(code);
    // While less than 10 turns and not a winner
    while (i < 10 && winner == false)
        {
        // Call Guess Function
        getGuess(guess, i, j);
        // Call Display Function
        displayFeedback(guess, code, i, j, feedback);
        // Call Is It Win Function
        winner = isItWin(feedback, code, i);
            // If winning before the 10th turn
            if (winner == true)
            {
                cout << "Yay, you won!";
                cout << endl;
            }
            // If lost
            if (winner == false && i == 9)
            {
                cout << "Sorry, you lose";
                cout << endl;
                cout << "Code was: " ;
                displaySecretCode(code);
            }
        i++;
        j++;
        }
    system ("pause");
    return 0;
}

// Set Secret Code Function
void setSecretCode(char code[])
{
    // Declare Variables
    string colors = "RGBYO";
    int pos;
    // Randomly Grab
    srand(time(NULL));
    pos = rand() % 5;
    code[0] = colors[pos]; 
    // Call Remove Color Function
    removeColor(code, colors, pos);

    // Randomly Grab
    srand(time(NULL));
    pos = rand() % 4; 
    code[1] = colors[pos];
    // Call Remove Color Function
    removeColor(code, colors, pos);

    // Randomly Grab
    srand(time(NULL));
    pos = rand() % 3; 
    code[2] = colors[pos]; 
    // Call Remove Color Function
    removeColor(code, colors, pos);

    // Randomly Grab
    srand(time(NULL));
    pos = rand() % 2; 
    code[3] = colors[pos];
    // Call Remove Color Function
    removeColor(code, colors, pos);
}

// Remove Color Function
void removeColor(char code[], string & colors, int pos)
{
    // Declare Variables
    string temp;
    int j = 0;

    // Create New Color String
    while (j<colors.length())
    {
        if (j!=pos)
        {
            temp = temp + colors[j];
        }
        j++;
    }
    colors = temp;
}

// Get Guess from User Function
void getGuess(char guess[][4], int i, int j)
{   
    cout << endl;
    cout << "Guess: ";
    cin >> guess[i][0] >> guess[i][1] >> guess[i][2] >> guess[i][3];
}

// Display Feedback Function
void displayFeedback(char guess[][4], char code[], int i, int j, char feedback[][4])
{
    // Display User's Guess
    cout << j << ". "<< "[" << " " << guess[i][0] << " " << guess[i][1] << " " << guess[i][2] << " " << guess[i][3] << "]";
    cout << endl;

    // Display Feedback if in wrong place
    if (guess[i][0] == code[1] || guess[i][0] == code[2] || guess[i][0] == code[3])
    {
        feedback[i][0] = '0';
        cout << "     " << feedback[i][0];
    }


    if (guess[i][1] == code[0] || guess[i][1] == code[2] || guess[i][1] == code[3])
    {
        feedback[i][1] = '0';
        cout << " " << feedback[i][1];
    }

    if (guess[i][2] == code[0] || guess[i][2] == code[1] || guess[i][2] == code[3])
    {
        feedback[i][2] = '0';
        cout << " " << feedback[i][2];
    }

    if (guess[i][3] == code[0] || guess[i][3] == code[1] || guess[i][3] == code[2])
    {
        feedback[i][3] = '0';
        cout << " " << feedback[1][3];
    }

    // Display Feedback if in Right Place
    if (guess[i][0] == code[0])
    {
        feedback[i][0] = '1';
        cout << "     " << feedback[i][0];
    }

    if (guess[i][1] == code[1])
    {
        feedback[i][1] = '1';
        cout << " " << feedback[i][1];
    }

    if (guess[i][2] == code[2])
    {
        feedback[i][2] = '1';
        cout << " " << feedback[i][2];
    }

    if (guess[i][3] == code[3])
    {
        feedback[i][3] = '1';
        cout << " " << feedback[i][3];
    }

    cout << endl;
}

// Display the Secret Code
void displaySecretCode(char code[])
{
    cout << code[0] << code[1] << code[2] << code[3];
    cout << endl;
}

// Determine if it is a Win
bool isItWin(char feedback[][4], char code[], int i)
{
    bool win;
    if (feedback[i][0] == '1' && feedback[i][1] == '1' && feedback[i][2] == '1' && feedback[i][3] == '1')
    {
        win = true;
    }
    else
    {
        win = false;
    }
    return win;
}

Dani AI

Generated

Immediate cause and quick fix
As pointed out, the missing character on the first pass is a simple indexing typo: one of the outputs prints from the wrong feedback row (uses the literal index 1 instead of the current-guess index). When the loop index is 0 that prints an uninitialised char (so nothing appears); when the loop index is 1 the same statement suddenly points at the populated row and looks correct. Correcting that index makes the observed symptom go away.

Other bugs and hardening to apply

  • Initialise the loop/win state: bool winner = false; — leaving winner uninitialised is undefined behaviour and can make the loop act unpredictably.
  • Seed rand once only: call srand(time(NULL)) once (for example in main) and remove repeated srand calls inside setSecretCode. Re-seeding inside the function can make the random choices poor or repeatable if calls happen within the same second.
  • Build feedback completely before printing: compute the four feedback symbols into a local buffer (initialise it to a known value), then print that buffer. That avoids partially-printed rows and makes debugging easier. The current code prints as it discovers matches, which can expose uninitialised slots.
  • Keep indexing consistent: maintain one loop counter and compute the display number from it (e.g. display = i+1) instead of carrying a separate j.

Optional improvements
If duplicates might be allowed later, switch to a two-pass feedback algorithm (mark exact matches first, then mark color-only matches while tracking used positions) to avoid double-counting. For better randomness and clearer code, consider C++11’s <random> and std::shuffle or use std::vector/std::string instead of raw arrays.

Fixing the index typo plus initialising winner and moving the seed will remove the strange first-guess behaviour and make the program deterministic and easier to maintain.

Line 152 you are using 1for the first index, it should be i. cout << " " << feedback[i][3];

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.