编程语言

img skyinter

解答C++作业03

发表于2004/10/26 12:10:00  601人阅读

分类: Crazy Soul For C++

#include<cstdlib>
#include<ctime>
#include<string>
#include<iostream>
#include<conio.h>
using namespace std;

const int SECRET_SIZE=10; // size of secret number array
const int GUESS_SIZE=4; // size of guess number array

void initialize_secret( int secret[] )
{
 int i; 
 srand((int)time(0));
 for (i=0;i<SECRET_SIZE;i++)
 {
  secret[i]=(rand())%10;
 }

}//use time as seeds

void read_guess( int guess[] )
{
 string str;
 char ch;int i=0;
 
 cout<<"guess:"<<endl;
 do{
 

  ch=getch();

  if(ch>='0'&&ch<='9')
  {
   putchar(ch);
   putchar(' ');
   str=str+ch;i++;
  }//ignore other input
  
 
 // if(ch==13) cout<<endl;

 }while(i<4);
 guess[0]=(int)str[0]-48;
 guess[1]=(int)str[1]-48;
 guess[2]=(int)str[2]-48;
 guess[3]=(int)str[3]-48;
 cout<<endl;
}


bool no_match(int secret[], int guess[] )
{
 int i,j,cowCount=0,bullCount=0;
 
 for(i=0;i<4;i++)
 {

  for(j=0;j<4;j++)
  {
   if(secret[i]==guess[j])
   {
   
    if(i==j) bullCount++;else cowCount++;

    break;//since the 4 number are different;
   }
  }//end for
 }//end for
 cout<<"bull:"<<bullCount<<"   cow:"<<cowCount<<endl;

 if (bullCount==4) return false;
 else return true;
}

void display(int secret[])
{
 int i;
 for(i=0;i<4;i++)
  cout<<secret[i]<<"  ";
 cout<<endl;
}

bool same(int secret[])
{
 int i,j;
 for(i=0;i<4;i++)
 for(j=i+1;j<4;j++)
  if(secret[i]==secret[j]) return true;
 return false;
}

int main()
{
 int secret[SECRET_SIZE];
 int guess[GUESS_SIZE],guessTime=0;

 do{
  initialize_secret(secret);
 }while(same(secret));//make sure the numbers are different

 cout<<"Melcome to MOO!!!!!!"<<endl;
 cout<<"***************************************************************/n"
    "Moo is a guessing game imported from England./n"
    "The computer picks a number consisting of four distinct decimal digits./n"
    "YOU guess four distinct digits being scored on each guess./n"
    "A /"cow/" is a correct digit in an incorrect position. /n"
    "A /"bull/" is a correct digit in a correct position./n"
       "The game continues until YOU guesses all the number.(a score of four bulls)/n"
       "Input four 0 to show secret. :)/n"
    "enioy it!!!!!! :)/n"
    "***************************************************************/n"<<endl;
 //description

 do{ 
  read_guess(guess);
  guessTime++;
  if (guess[0]==0&&guess[1]==0&&guess[2]==0&&guess[3]==0)
   display(secret); 
 }while(no_match(secret,guess));

 cout<<"YOU finally succeed!"<<endl;
 cout<<"YOU have tried "<<guessTime<<" times!"<<endl;
 cout<<"Welcome to replay this game!!!!!!"<<endl;
 return 0;
}

阅读全文
0 0

相关文章推荐

img
取 消
img