mercredi 15 mai 2013

Mastermind, a small evolution to map with the true rules!

In my previous post about the Mastermind game, I didn't implement the real rules and my daughter said that I should use 'W'hite & 'B'lack peg as in the real game to say if a color is correctly placed, misplaced and empty if there is nothing to say !

So I added a short description of the rules, color code, number of allowed try, etc ....


cout << "Code of " << TheHiddenCode.size() << " peg" << endl;
cout << "Number of try to guess " << nb_line << endl;
cout << "Color are ", for_each(color_code.begin(), color_code.end(), [](const color_t& c){cout << c.second << " " ;}), cout << endl;


In the main loop, the 'answer' is now a vector of char to store our 'W' and 'B' peg!...


while( exact < TheHiddenCode.size() && nb_try < nb_line) {
cout << "\n\nguess--> ", cin >> guess;
if(guess.size() == 4) {
exact = color = 0;
transform( begin(TheHiddenCode), end(TheHiddenCode),
begin(guess), begin(answer),
Count( TheHiddenCode, color, exact ) );
cout << "Answer => " << "Incorrect place " << color << " Correct place " << exact << " : " ,
copy(answer.begin(), answer.end(), ostream_iterator<char>(cout, " ")),
cout << endl;
nb_try++;
} else {
cout << "incorrect number peg on the line" << endl;
}
}


And finally I updated my 'Count' class to check if a peg in the guess, if well or misplaced ....


struct Count {
Count( hidden_code_t code, int& incorrect_place, int& exact )
: incorrect_place_(incorrect_place), exact_(exact=0), code_(code) { }
char operator()( color_t c, char g ){
bool correct_place = (c.second == toupper(g));
if(correct_place) { //Argh, conditionnal are ugly !
exact_++;
return 'W';
} else {
//does that color be somewhere else in the code...
auto f = std::find_if(begin(code_), end(code_), [&g](const color_t& tobecheck_) { return (tobecheck_.second == toupper(g));} );
auto misplaced = (f != code_.end());
incorrect_place_ += (int) (misplaced);
if(misplaced)
return 'B';
else
return ' ';
}

}
~Count(){
}

int &incorrect_place_, &exact_;
hidden_code_t code_;
};


Based on that work, I will present later an API and Async Engine.

Aucun commentaire :

Enregistrer un commentaire