解答C++作业03

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值