HANG MAN GAME IN C++(using strings ,vectors,algorithms)


#include<iostream>
#include<vector>//header for vector class
#include<string>//header for string class
#include<algorithm>//header for using pre degined algorithms
#include<cstdlib>//for using srand() function
#include<ctime>//for inserting time in srand()
using namespace std;




int main()
{
  vector<string>word;//declaring vector named word

  word.push_back("abacus");//inserting values in vector

  word.push_back("english");//inserting values in vector

  word.push_back("germany");//inserting values in vector

  srand(static_cast<unsigned int>(time(0)));

  random_shuffle(word.begin(),word.end());//shuffling member of vectors

  string theword=word[0];//assigning word[0] to theword

  string used="";//tells which characters are used

  string soFar(theword.size(),'-');//print '-' equal to total number of characters in words

  char guess;//enter your guess

  int choice=0;//counter for total choices

  if(word[0]=="abacus"){//for hint purpose this is used
  cout<<"this device is old computing machine "<<endl;
  }
  if(word[0]=="english"){//for hint purpose this is used
  cout<<"this is some widely spoken language "<<endl;
  }
  if(word[0]=="germany"){//for hint purpose this is used
  cout<<"this is aname of european country "<<endl;
  }


  while((choice<=8) && (soFar!=theword)){//while loop only execute if choices made are less than 8 //and our word !=theword
 
 cout<<endl<<"the words that we have used = "<<used<<endl;
 cout<<"the word guessed so far = "<<soFar<<endl;
 cout<<endl<<"enter the  character "<<endl;
 cin>>guess;
 while(used.find(guess)!=string::npos){//while loop runs only if guessed charcter is found in //string used else return string::npos
 cout<<"you have already guesses this word "<<endl;
 cout<<endl<<"enter the word "<<endl;
 cin>>guess;

 }
 used+=guess;//used for concatenation purpose to teel which words we have used
 choice++;//increment choice
 cout<<endl<<"you have only "<<8-choice<<"chances left "<<endl;//tells how many choices //are left
 if(theword.find(guess)!=string::npos){//oly executes if our guess is in the word
 cout<<"you entered the right guess "<<endl;
 for(int x=0;x<theword.size();x++){
 if(guess==theword[x]){//if our guess is  equal to character in that place in string theword
 soFar[x]=guess;//then replace '-' at that place in string soFar with that character
 }
 }
  
  }
 else{
 cout<<endl<<endl<<"sorry wrong guess "<<endl;
 }
  }
  if(choice<=8){//as our loop terminated before choice>9 this mean we guessed right
  cout<<"you guessed it right "<<endl;
  }
  else{
  cout<<"you are hanged"<<endl;
  }

  cout<<endl<<endl<<" the right guess = "<<word[0]<<endl;
}











Previous
Next Post »

Comments:

Disqus Shortname