I wrote a simple Mastermind game. Please take a look at it and tell me your comments:
Code:#include<iostream> #include<cstdlib> #include<iomanip> #include<ctime> #include<conio.h> #include<ctype.h> using namespace std; #define PADLEN 14 //For aligning output #define CHARNUM 3 //Number of characters to be guessed //Initializes screen and makes a random generated secret word void intitsecret(char s[CHARNUM]){ cout<<endl<<"Guess"<<setw(PADLEN)<<"Correct"<<setw(PADLEN)<<"Guess#"<<setw(PADLEN)<<"Misplaced"<<endl; tm *tmst; time_t t=time(NULL); tmst = gmtime(&t); srand(tmst->tm_sec); for(int i = 0; i<CHARNUM;i++){ char rnd =(rand()%26)+97; s[i] = rnd; } } //Gets a guess word from player bool getguess(char g[CHARNUM]){ for(int i =0;i<CHARNUM;i++){ char t= (char) _getch(); if(t==27) return true; //Escape to exit program //Making back space functional if(t==8 && i>0){_putch(8);i--;_putch(' ');_putch(8);} if((t>0)&& isalpha(t)&& !isdigit(t)){ t=tolower(t); _putch(t); g[i]=t; } else i--; } return false; } //Compares guessed work with secret word and shows the result. //In addition it returns true if the guessed and secret words matched. bool comp_show(char s[CHARNUM],char g[CHARNUM]){ static int count; count++; int cp=0; int mp=0; char t[CHARNUM]; strncpy(t,s,CHARNUM); for(int i=0 ;i<CHARNUM;i++) if(t[i]==g[i]){ t[i]='\0'; cp++; } for(int i=0 ;i<CHARNUM;i++) for(int j=0;j<CHARNUM;j++) if(t[i]==g[j]){ t[i]='\0'; mp++; } cout<<setw(PADLEN)<<cp<<setw(PADLEN)<<count<<setw(PADLEN)<<mp<<endl; if(cp==CHARNUM) return true; else return false; } int main(){ char g[CHARNUM+1]; char s[CHARNUM]; intitsecret(s); for(int i=0;i<40;i++){ if(getguess(g)) break; if(comp_show(s,g)){ //Player won cout<<"Correct! "; if(i>10) cout<<"Very good, you are very smart."<<endl; else if (10<i && i<30) cout<<"Not bad."<<endl; else cout<<"Not good, you should try to guess faster."<<endl; _getch(); exit(0); } } //Player lost or escaped cout<<endl<<"You lost! The word was: "; for(int i=0 ;i<CHARNUM;i++) _putch(s[i]); _getch(); return 0; }



LinkBack URL
About LinkBacks



