Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <windows.h>
- #include <stdlib.h>
- #include <time.h>
- #include <sstream>
- using namespace std;
- string code;
- string codeArr[9];
- int array[9];
- void explain()
- {
- cout<<"Welcome to Bulls and Cows!"<<endl;
- cout<<"--------------------------"<<endl;
- cout<<"The computer will generate a random 4 digit number with no repeating digits."<<endl;
- cout<<"The objective of the game is for you to guess that 4 digit number."<<endl;
- cout<<"The computer responds with how close your guess is to the number."<<endl;
- cout<<"Bulls = Number of correct digits in the correct place"<<endl;
- cout<<"Cows = Number of correct digits in the wrong place"<<endl;
- cout<<"Good luck! Press any key to continue."<<endl;
- system("pause>nul");
- }
- void generateNumber()
- {
- srand(time(NULL));
- int temp;
- string tempString;
- for(int c=0;c<9;c++)array[c]=c+1;
- for(int c=0;c<9;c++)
- {
- int x=rand()%4+1;
- temp=array[c];
- array[c]=array[x];
- array[x]=temp;
- }
- for(int c=0;c<4;c++)
- {
- ostringstream convert;
- convert<<array[c];
- tempString=convert.str();
- code+=tempString;
- }
- for(int c=0;c<4;c++)
- {
- ostringstream convert;
- convert<<array[c];
- codeArr[c]=convert.str();
- }
- }
- int game()
- {
- int turnCount=1;
- for(int c=0;c<10;c++)
- {
- string guess="";
- int bullCount=0, cowCount=0;
- cout<<"Attempt "<<turnCount<<endl;
- cout<<"Enter your guess: "<<endl;
- cin>>guess;
- while(guess[0]==guess[1]||guess[0]==guess[2]||guess[0]==guess[3]||guess[1]==guess[2]||guess[1]==guess[3]||guess[2]==guess[3])
- {
- cout<<"Your guess should not have repeating digits! Try again."<<endl;
- cout<<"Enter your guess: ";
- cin>>guess;
- }
- if(c==9&&guess!=code)
- {
- cout<<"You ran out of attempts! Better luck next time! The code was "<<code<<endl;
- return 0;
- }
- if(guess==code)
- {
- cout<<"Congratulations! You got the code in "<<turnCount<<" attempts! You win!"<<endl;
- return 0;
- }
- turnCount++;
- for(int c=0;c<4;c++)
- {
- if(guess[c]==code[c])
- bullCount++;
- int num=guess.find(codeArr[c]);
- if(num!=-1)cowCount++;
- }
- cout<<"Bulls: "<<bullCount<<endl;
- cout<<"Cows: "<<cowCount<<endl;
- cout<<"-----------------"<<endl;
- }
- }
- int main()
- {
- explain();
- generateNumber();
- game();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement