Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
int numgen1(int a)
{
int b;
do{
b=rand()%10;
}while(b==a);
return b;
}
int numgen2(int a,int b)
{
int c;
do{
c=rand()%10;
}while(c==a||c==b);
return c;
}
int numgen3(int a,int b,int c)
{
int d;
do{
d=rand()%10;
}while(d==a||d==b||d==c);
return d;
}
int numcheck(int w,int x,int y,int z,int a,int b,int c,int d,char plrname[])
{
int bulls=0,cows=0;
if(w==x||w==y||w==z)
{
printf("invalid entry!! Closing game...");
exit(0);
}
if(w==b||w==c||w==d)
cows=cows+1;
else if (w==a)
bulls=bulls+1;
if(x==a||x==c||x==d)
cows=cows+1;
else if (x==b)
bulls=bulls+1;
if(y==a||y==b||y==d)
cows=cows+1;
else if (y==c)
bulls=bulls+1;
if(z==a||z==b||z==c)
cows=cows+1;
else if (z==d)
bulls=bulls+1;
if(bulls==4)
{
printf("Correct answer!!!! You won!! Congratulations %s",plrname);
return 1;
}
else
printf("Bulls=%d\nCows=%d\nTry Again!!\n",bulls,cows);
}
int main()
{
int w,x,y,z,a,b,c,d,try=0,f;
char plrname[20],ch1,ch;
srand(time(0));
clrscr();
printf("Welcome to Bulls and Cows game\nEnter your name to continue\n");
gets(plrname);
printf("\nMAIN MENU\nPress P for Play Game\nX for EXIT\n");
scanf("%c",&ch);
a=rand()%10;
b=numgen1(a);
c=numgen2(a,b);
d=numgen3(a,b,c);
while(1)
{
++try;
switch(ch)
{
case 'p': printf("TRY NO. %d\n",try);
printf("Enter 4 Digits\n");
scanf("%d%d%d%d",&w,&x,&y,&z);
f=numcheck(w,x,y,z,a,b,c,d,plrname);
if(f==1)
{
getch();
exit(0);
}
if(try==5||try==10||try==15)
{
printf("Press Y for correct answer\n");
scanf("%c",&ch1);
if(ch1=='Y'||ch1=='y')
{
printf("The Correct answer was %d%d%d%d",a,b,c,d);
getch();
exit(0);
}
}
else if(ch1=='N'||ch1=='n')
break;
else
continue;
case 'c': break;
case 'x': exit(0);
}
}
}