/*
Name: cow_bull.cpp
Purpose: to create a working example of a console cow & bull game.
*/
#include<iostream>
#include<stdexcept>
#include<sstream>
#include<ctime>
#include<cstdlib>
usingnamespace std;
//=============================================================================
struct Cow_bull{
Cow_bull(string g,string a)
:guess(g),answer(a),cow(0),bull(0){
calculate_bull();
calculate_cows();
}
void set_guess(string g){
guess=g;
bull=0; //reset to zero for each guess
cow=0; //reset to zero for each guess
g2=""; //resetting string for each guess
a2=""; //resetting string for each guess
calculate_bull();
calculate_cows();
}
int get_cow() const{return cow;}
int get_bull() const{return bull;}
private:
string guess;
string answer;
string g2;
string a2;
int cow;
int bull;
void calculate_bull(){
for(unsigned i =0; i<guess.size();++i){
if(guess[i]==answer[i]){++bull;}
else{
g2=g2+guess[i]; //saving this wrong guess to check for cows
a2=a2+answer[i]; //saving this answer to check for cows
}
}
}
void calculate_cows(){
for(unsigned i =0; i<g2.size();++i){
for(unsigned ii =0; ii<g2.size();++ii){
if(g2[i]==a2[ii]){
++cow;
a2[ii]=0; /*ensuring that I do not check this answer
right twice.*/
break;
}
}
}
}
};
//=============================================================================
ostream& operator<<(ostream& os, Cow_bull& cb){
return os<<"you had "<<cb.get_bull()<<" bulls and "
<<cb.get_cow()<<" cows.";
}
//=============================================================================
string create_random_answer(){
srand(time(0));
stringstream reply;
for(int i=0; i<4;++i){
reply<<int(rand() % 10);
}
return reply.str();
}
//=============================================================================
bool just_number(string s){
for(unsigned i=0; i<s.size();++i){
if(!isdigit(s[i]))returnfalse;
}
returntrue;
}
//=============================================================================
int main()try{
cout<<"\n\nTry to guess a four number sequence. If you guess the right number\n";
cout<<"in the right location you will be awarded a bull. If you guess\n";
cout<<"the right number in the wrong location you receive a cow. The goal is\n";
cout<<"to get four bulls.\n\n";
string guess;
string answer=create_random_answer();
Cow_bull cb(guess,answer);
while(cb.get_bull()!=4){
do{
cout<<"\nEnter a four number string e.g. 1234 :";
cin>>guess;
}while(guess.size()!=4 || !just_number(guess));
cb.set_guess(guess);
cout<<cb<<'\n';
}
return 0;
}
catch(exception& e){
cerr<<e.what()<<endl;
return 1;
}
catch(...){
return 2;
}