dimanche 25 février 2018

Checking individual digits and copying valid ones by looping

I am creating a "CodeBreaker" game. In this game, the computer randomly generates a secret numeric code that is three digits in length, composed of digits ranging from one through six. The player's task is to guess all of the digits of the code, in the correct order. After twelve guesses, the game is over.

The computer checks the digits guessed by the player, comparing each to ones in the secret code, and determines whether each digit in the player's guess is of the correct identity and in the correct place, or whether each digit is of the correct identity but is not in the correct place. With each guess, it counts the number of “correct” and “misplaced” digits, and prints these totals to the screen, alongside the player's guess. This is the section I am having trouble with. I need to loop through the player's input, checking each digit, then copy the valid digits using an if-else statement.

#include <iostream>
#include <cstdlib>
#include "Project1.h"

using namespace std;

string get_player_code() {


    string player_code = string(CODE_LENGTH, '0');

    string player_input;                            

    char digit;

    bool valid_code = false;                            
    bool invalid_digit_entered;                     

while ( !valid_code ) {

    invalid_digit_entered = false;

    cout << "Enter Code: ";
    cin >> player_input;

    /* Is code too short or too long? */

    if ( player_input.size() != CODE_LENGTH ) {

        cout << "ERROR: Code must be exactly " << CODE_LENGTH << " digits long!\n\n";

    }

    /* If not, loop through player_input and check each digit, copying validated digits into player_code */

    else {

        // *** INSERT CODE HERE ***

        valid_code =  true;

         }

} // End while()

return player_code;
}

Aucun commentaire:

Enregistrer un commentaire